如何在vc中完成串的倒序输出?如果可以的话,请麻烦写一下代码?
假如我的程序是:
#include <iostream>
string str="abcde";
我想输出"edcba",怎么写呢?谢谢!
假如字符串长度为n,把字符串的第0个和第n-1个字符,第1个和第n-2个字符,第2个和第n-3个字符,……依次交换一下不就可以了吗?
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "abcdefg";
int len = str.size();
for(int i = 0; i < len / 2; i++)
{
char c = str.at(i);
str.at(i) = str.at(len - i - 1);
str.at(len - i - 1) = c;
}
cout << str << endl;
return 0;
}^_^建立2个字符串数组,将这个字符串数组赋上你现在的字符串的值,然后判断字符串的结束符,然后就反过来赋给另外一个字符串就是了吧
设置一个指针,先把它指向str的最后一个字符,然后再逐渐输出指针-1的字符
非常感谢上面三位朋友的回答,
我就是不懂得如何在c++中取出单个的字符串是用哪个函数,又不懂得查msdn才来发问的,没想到这么快就有这么热心的朋友来解答了,再次谢谢大家。特别感谢steedhorse 兄!!!
按照前面两位朋友的想法,我仿steedhorse 兄的程序,也做了一段代码,请大家看看可不可取啊?我运行成功了。
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "abcdefg",str1;
int len = str.size();
for ( int i = len-1 ; i >= 0 ; i-- )
{
char c = str.at(i);
str1 = str1 + c;
}
cout << "str1=" << str1 <<endl;
return 0;
}