题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。
为简单起见,标点符号和普通字母一样处理。
例如输入I
am a student.,则输出student. a am I。
- #include <iostream>
- #include <string>
- void MyReverse(std::string& str, int i,int j)
- {
- for (; i < j; ++i,--j)
- {
- char temp = str[i];
- str[i] = str[j];
- str[j] = temp;
- }
- }
- void Reverse(std::string& str)
- {
- MyReverse(str,0,str.size()-1);
- int begin = -1,end = -1;
-
- int i = 0;
- while (str[i])
- {
- while (str[i] && (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')) i++;
- begin = i;
- while (str[i] && str[i] != ' ' && str[i] != '\t' && str[i] != '\n') i++;
- end = i-1;
- reverse(str,begin,end);
- }
- }
- int main()
- {
- std::string str = "I am a student.";
- Reverse(str);
- std::cout << str << std::endl;
- }
阅读(444) | 评论(0) | 转发(1) |