Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 35 - String Reversal

C Exercise 35

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Reverse a string, for example reverse the string "www.runoob.com" to "moc.boonur.www".

**Analysis:** None.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

void

reverse

(

char

s

)

{

// Get the string length

int

len

=

0

;

char

p

=

s

;

while

(

p

!=

0

)

{

len

++;

p

++;

}

// Swap ...

int

i

=

0

;

char

c

;

while

(

i

<=

len

/

2

1

)

{

c

= *

(

s

i

)

; *

(

s

i

)

= *

(

s

len

1

i

)

; *

(

s

len

1

i

)

=

c

;

i

++;

}

}

int

main

(

)

{

char

s

[

]

=

"

www.runoob.com

"

;

printf

(

"

'%s' =>

\

n

"

,

s

)

;

reverse

(

s

)

;

// Reverse the string

printf

(

"

'%s'

\

n

"

,

s

)

;

return

0

;

}

The output of the above example is:



'www.runoob.com' =>

'moc.boonur.www'

100 Classic C Language Examples 100 Classic C Language Examples