String Manipulation in C / C++ – 2 : reverse a string

Question 2. We wish to reverse the given string.

Solution.

We can use the strrev function from the string header, or proceed as follows:

—-

The procedure for reversing a string traverses through the length of the string, swapping the first with the last character, the 2nd with the 2nd-from-last character, and so on, until it reaches the middle of the string, at which point it terminates.

—-

void reverse ( char *s)

{

for (int i = 0, j = strlen (s) – 1; i < j; i++, j–)

{

//swap s[i] with s[j]

char temp;

temp = s[i];

s[i] = s[j];

s[j] = temp;

}

}

—-

Again, those preferring to use pointer notation for accessing string characters may proceed as follows:

—-

void reverse ( char *s)

{

for ( int i = 0, j = strlen(s) – 1; i < j; i++, j==)

{

//swap *(s+i) and *(s+j)

char temp;

temp = *(s+i);

*(s+i) = *(s+j);

*(s+j) = temp;

}

}

—–

Again, one should check whether cases such as the null string are handled properly by the written code. Also, one should also check whether even-length and odd-length strings are handled appropriately by the code.

—-

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: