C++ string Reversing the order of a string of characters.

Description

C++ string Reversing the order of a string of characters.

#include <iostream>
#include <string>

using std::string;

string reverse(string str1);/*from w  w w  .  j a  v a2s  .c om*/

int main()
{
  string sentence {"this is a test"};

  std::cout << std::endl << "Your sequence in reverse order is:\n";
  std::cout << reverse(sentence) << std::endl;

  std::cout << "Here is a demonstration of reverse() working with a C-style string:\n";

  char stuff[] {"abcdefg"};                      // C-style string
  std::cout << std::endl << "The original string is: \"" << stuff << "\"" << std::endl << "Reversed it becomes: \"" << reverse(stuff) << "\"" << std::endl;
}

string reverse(string str){
  char temp {};

  int len {str.length()};

  for (int i {}; i < str.length() / 2; ++i){
    temp = str[i];
    str[i] = str[len - i - 1];
    str[len - i - 1] = temp;
  }
  return str;
}



PreviousNext

Related