#include<iostream>
using namespace std;
int main(){
int t,i;
char a[1000],p;
cin >> t;
cin.ignore(1, '\0');
while (t--){
i = -1;
cin.getline(a, 1000);
for (int n = 0; n <=strlen(a); n++){
i++;
if (a[n] == ' ' || a[n] == '\0'){
int l = 0;
int r = i / 2;
int j = n - i; //n-i 为单词第一个字母
while(r--){
p = a[n - 1+l];
a[n - 1+l] = a[j ];
a[j] = p;
l--;
j++;
}
i = -1;
}
}
for (int n = 0; n < strlen(a); n++)
cout << a[n];
cout << endl;
}
}
本例中,字符串中单词的长度知道,循环交换的次数为(int)r/2次,循环次数确定,用while比用for方便
用cin.getline(a,100)获得字符串,在数组的a[strlen(a)]处存放结束符\0
使用reverse()函数:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
char s[2001];
char *c;
int t;
cin >> t;
cin.ignore(1, '\n');
while (t--){
cin.getline(s, 2001);
c = &s[0];
for (int n = 0; n <= strlen(s); n++){
if (s[n] == ' ' || s[n] == '\0'){
reverse(c, &s[n]);
c = &s[n + 1];
}
if (s[n] == '\0')
c = NULL;
}
cout << s << endl;
}
}