杭电OJ1062 Text Reverse

#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;
	}
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值