您的位置:首页 > 其它

杭电OJ1062 Text Reverse

2016-07-19 17:16 639 查看
#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
== ' ' || a
== '\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
;
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
== ' ' || s
== '\0'){
reverse(c, &s
);
c = &s[n + 1];
}
if (s
== '\0')
c = NULL;
}
cout << s << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: