'How to write c++ code to reverse a string without using inbuilt function?
I have write this code. It does not show any error but string is not reversed.please let me know where i have made the mistake? I'm using codeblock to write code and GCC compiler. I have created two functions reverseString and printString, the printString function is working but reverseString is not working. what can i do?
#include <iostream>
#include<string>
using namespace std;
void reverseString(string s, int iNode, int lNode){
while(iNode < lNode){
char temp = s[iNode];
s[iNode] = s[lNode];
s[lNode] = temp;
iNode++;
lNode--;
}
}
void printString(string s, int n){
for(int i=0; i<n; i++){
cout << s[i];
cout << endl;
}
}
int main() {
string s;
cout << "Type String To Reverse: \n";
cin >> s;
cout << "String In Actual Order: \n";
printString(s,s.length());
reverseString(s, 0, s.length()-1);
cout << "String In Reverse Order: \n";
printString(s,s.length());
return 0;
}
Solution 1:[1]
This function accepts an object of the type std::string by value
void reverseString(string s, int iNode, int lNode){
while(iNode < lNode){
char temp = s[iNode];
s[iNode] = s[lNode];
s[lNode] = temp;
iNode++;
lNode--;
}
}
It means that it deals with a copy of the string used as an argument and changes the copy instead of the original string.
You have to declare the parameter as having reference type
void reverseString(string &s, int iNode, int lNode){
while(iNode < lNode){
char temp = s[iNode];
s[iNode] = s[lNode];
s[lNode] = temp;
iNode++;
lNode--;
}
}
The function could be defined simpler (without using standard features as for example std::swap) the following way
std::string & reverseString( std::string &s )
{
for ( std::string::size_type i = 0, n = s.size(); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
And the function can be called like
cout << "String In Reverse Order: \n";
std::cout << reverseString( s ) << '\n';
Without using the loop you could define the function just the following way
std::string & reverseString( std::string &s )
{
return s.assign( s.rbegin(), s.rend() );
}
As for your own function printString then it could be defined at least like
std::ostream & printString( const std::string &s, std::ostream &os = std::cout )
{
for ( char c : s )
{
os << c;
}
return os;
}
and can be called like
printString( s ) << '\n';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
