C++

Name Reversing in c++

it’s one of the interview questions that i had faced before.

the program should take a name from the user like “Ahmed Yehia Ibrahim” and reverse each character in every word in the string.

input: Ahmed Yehia Ibrahim

output: demhA aiheY miharbI

#include <iostream>
#include <string>
using namespace std;

string convet(string name)
{
  string newName;
 
 for (int i = 0; i < name.length(); i++)
 {
    if (name[i] == ' ')
    {
      for (int j = i-1; j >= 0; j--)
      {
        if (name[j] != ' ')
            newName += name[j];
        else
            break;
      }
      newName += ' ';
    }
    else if (i == name.length()-1)
    {
      int j = i;
      while ( j >= 0 && name[j] != ' ')
      {
        newName += name[j];
        j--;
      }
    }
  }
 return newName;
}
int main()
{
  string name;
 
  cout << "Enter Your Name: ";
  getline(cin,name);
  cout << "Name After Reversing: "<< convet(name) << endl;
  return 0;
}

Capture

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s