String
May 12, 2013 at 6:55pm UTC
How to write a function that reverses a string but not the positions of the null terminator?
May 12, 2013 at 7:08pm UTC
create a second string that is either empty and same size as the other string or set it equal to the other string. and then loop backwards and put those characters into the new string. You will also need a number counting up from 0 for the second string
eg
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main ( int argc , char ** argv )
{
std::string str("Giblit" ), str2 = str;
unsigned int j = 0;
for ( signed int i = str.size() -1 ; i > -1; i-- )
{
str2[j] = str[i];
j++;
}
std::cout << "Normal String: " << str << std::endl;
std::cout << "Backward String: " << str2 << std::endl;
}
Normal String: Giblit
Backward String: tilbiG
Process returned 0 (0x0) execution time : 0.191 s
Press any key to continue.
Last edited on May 12, 2013 at 7:09pm UTC
May 12, 2013 at 7:09pm UTC
1 2 3 4 5 6
#include <algorithm>
/*....*/
char x[10];
std::strcpy(x, "Hello" );
std::reverse(x, x + std::strlen(x));
std::cout << x;
or if you want to do it without standart library:
1 2 3 4 5 6
void reverse(char * first, char * last)
{
while ((first != last) && (first != --last)) {
std::swap(*first++, *last);
}
}
@
giblit there can be no null terminator in std::string.
Last edited on May 12, 2013 at 7:12pm UTC
Topic archived. No new replies allowed.