Question:
c++ string question?
jkim972
2007-04-03 21:11:45 UTC
if I have a string, let's say "something",
How would I use loop and string operations to make it print "something" backward,
like gnihtemos?

This is the last part of my programming HW and I can't figure it out. If anyone can help, I'd appreciate it
Thank you
Five answers:
Silver_Sword
2007-04-03 21:43:02 UTC
string a = "something";



for(int i = a.length( ) -1; i >=0; i--)

{

cout << a[i];

}



To do this you do NOT have to use the "cstring" header file. You the string header file as follows:



#include
SleepWalker
2007-04-04 04:59:44 UTC
To do this you must use "cstring" header file. It contains a function called strlen() , so then you can calculate the number of charactors of the string and reverse it by a for loop.

Here's the code:



#include

#include

using namespace std;

int main() {

char name[]="something";





for (int r =strlen(name); 0<=r; r=r-1 )

{ cout << name[r];

}

cout<<"\n";







return 0;

}
mahesh k
2007-04-04 05:33:08 UTC
get the length of string. after getting length loopfrom last character to first character
Walt Kolo
2007-04-04 13:50:08 UTC
Easily done by;



[code]

#include

#include



int main()

{

string reverse;

string test="hellome";

for(int x=test.length()-1; x>-1; x--)

{

reverse+= test.at(x);

cout<
}

cin.get();

return 0;

}

[/code]
Smart_Guy
2007-04-04 04:14:09 UTC
go to http://vrajesh.co.nr for free tutorial regardinng programming languages


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...