In: Computer Science
c++
I want to flip the string when it's string type.
For example, if it is 'apple', I would like to print 'elppa'.
how can i do?
Solution for the problem is provided below, please comment if any doubts:
There are a number of ways to flip a string in C++, based on your requirements you can use it, a function .reverse() is available under "algorithm" header, you can use pointers, using string iteration, etc. Also you can create a function to perform the job done.
The C++ program that flip a string using a defined function:
//add the header files
#include <iostream>
#include <string>
using namespace std;
//the function to perform the flip of a string
//Take thes string as reffernce to make the strinf flipped
void flipString(string &instr)
{
//Find the length of the string
int len = instr.length();
/*flip the characters using a for loop
//Flip the characters that are at same distance
//from begining and end to make the flip
*/
for (int i = 0; i < len / 2; i++)
{
//perform the dwap
char temp
=instr[i];
instr[i] =instr[len - i - 1];
instr[len - i - 1] = temp;
}
}
//the main to check the function
int main()
{
//test string
string str = "apple";
//perform the flip
flipString(str);
//output the flipped string
cout << str<<endl;
return 0;
}
Output: