*将一句话中的单词进行倒置,且不改变原标点符号的位置**
示例:
输入:
“i like you.”
输出:
“‘you. like i”
废话不多说,先放代码。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<int>v;//创建一个数组,用来存储空格的在字符串中的位置。
int pos = 0;//创建一个变量来记录空格位置信息。
string test;//创建一个字符串
getline(cin, test);//用getline输入一行带有空格的字符串
while ((pos = test.find(" ", pos)) != string::npos)//这个循环找出所有的空格位置
{
v.push_back(pos);//把空格位置信息放入数组中
pos++;
}
vector<int>::reverse_iterator rit = v.rbegin();//用迭代器从后往前遍历空格的位置
for (; rit != v.rend(); rit++)//遍历迭代器
{
for (pos = *rit + 1; test[pos] != ' ' && test[pos] != *test.end(); pos++)
{
cout << test[pos];
}
cout << " ";
}
for (int i = 0; test[i] != ' ' && test[i] != '\0'; i++)
{
cout << test[i];
}
}
前面的创建过程已经注释在代码中。
最重点的就是这一部分
for (; rit != v.rend(); rit++)//遍历迭代器
{
for (pos = *rit + 1; test[pos] != ' ' && test[pos] != *test.end(); pos++)
{
cout << test[pos];
}
cout << " ";
}
遍历迭代器找出空格的位置,然后利用一个for循环。
把空格之后的字符串部分输出,在碰到下一个空格或是“\0”时循环结束。
然后继续遍历出一个空格的位置,往复上面的操作。
for (int i = 0; test[i] != ' ' && test[i] != '\0'; i++)
{
cout << test[i];
}
这部分的代码则是写入开头第一段的字符串,
因为没有空格,且迭代器从后往前定义,故第一段字符串要最后用for循环输出。
以上就是我的关于逆置字符串的总结。
希望对你有所帮助。:)