Sunday, July 12, 2009

C++; reversing c-string...?

if we have only one parameter in a void function...and that parameter only accepts the name of array which contains a c-string....


in order to reverse a c-string...like yahoo to oohay...(ignoring any possible whitespaces)....


in the function do we depend on finding the null character to find the size of that array and then assign the first element to the last element of a new array and last to the first one...and go on..?


if we don't have the size and c-string size can be any number...


how do we assign the first element (i.e. character) to the last element of a new array (without knowing the size).. thx!

C++; reversing c-string...?
Because of the nature of the C-string, you don't need to be explicitly told the length of the string - but that doesn't mean you can't find it. Every string in C is ended by the character '\0', so all you have to do is count characters until you hit '\0'. Once you have the length, you can start moving characters accordingly. (NOTE: the '\0' character doesn't count towards the length of the string)





Now, I don't want to just give away the code, because I can sense this is part of an assignment for school, but I hope that piece of information will get the ball rolling.
Reply:If you are allowed to use STL, you can also use the reverse function.





void rev(char c[]) {


string s(c);


reverse(s.begin(), s.end());


strcpy(c, s.c_str());


}

jasmine

No comments:

Post a Comment