1.for循环实现字符串逆置 #include <iostream> using namespace std; int main() { string str; cout << "请输入一个字符串:" << endl; cin >> str; int j = str.length() - 1; //必须要放在输入字符串之后 for (int i = 0; i < j; i++) { int tmp = str[i]; str[i] = str[j]; str[j] = tmp; j--; } cout << str << endl; system("pause"); return 0; } 2.while循环实现字符串逆置 #include <iostream> #include <stdio.h> using namespace std; int main() { string str; int i = 0; char tmp; cout << "请输入一个字符串:" << endl; cin >> str; int j = str.length() - 1; while (i < j) { tmp = str[i]; str[i] = str[j]; str[j] = tmp; i++; j--; } cout << str << endl; system("pause"); return 0; }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280624.html