0

Anyone can help me to write a code in C++ to reverse a string.
Example:
i/p= " string with space "
o/p= " ecaps htiw gnirts "

Better if we use function or class.
Thanks in advance

4
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by template<>
0
#include <string>
#include <algorithm>

int main(){
  std::string text = "reversi mei!";
  std::reverse(text.begin(), text.end());
}

Edited by pseudorandom21: n/a

0

Sorry, I forgot to mention that the program ask the user to input the string that needed to be reversed. Also without using any in-build string function. i.e reverse etc.

0

Create an index at both ends of the string and swap characters, moving the indices closer until they meet. When they meet (or pass), the string will be completely reversed.

0

Thanks Narue for your kind help. I have one more doubt, how can I create the end index of the string?

0

It depends on which string type you use. For std::string the last index is s.size()-1 . For C-style strings, you'd need to count up to the null terminator with something like strlen: strlen(s)-1 .

0

try it in c first, just for fun. Here is something to get you started, complete the function, use algorithm described by Narue..

char *reverse( char *input)
{



}

Edited by template<>: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.