杭电OJ1062 Text Reverse

本文介绍两种字符串单词反转的方法:一种是通过循环交换字符实现;另一种利用C++标准库函数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;
	}
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值