Monday, July 27, 2009

C++ reverse_string?

Does anyone know the code for reverse string like "ABCD" comes out "DCBA" ?

C++ reverse_string?
here's a thought...





print the last letter of the string.





print the string without the last letter backwards





if the string is length 0, (like it will be after you print a) just don't do anything.
Reply:Make a new character array the size of the one you want to reverse.





Make a loop with two counters. One starts from 0 and goes to [ how many characters ] and the other goes from [ how many characters ] down to 0. Use the second counter to walk through the first normal array backwards, and on each cycle, take that character and put it into the new array at the index which is defined by the normal forward counter.





Psuedo code:


char newAr[ same size as orig ]


int i = 0


int j = [size of orig array] - 1





for( i, j ; i %26lt; [ size of orig array ] ; i++, j-- )


newAr[i] = origAr[j]
Reply:In C++, check out the reverse_iterator


No comments:

Post a Comment