使用<string>中字符串处理函数:
(1)、getline(istream &in,string &s):
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
(2)、int position=string.find("xxx"):
返回string中首次出现串xxx的下标位置给position
如果position == s.npos ,说明没有找到,C++用一个特别的标志npos标识;
其它用法:
int position=string.find("xxx",5);
从string的下标5后开始查找;
(3)、string.replace(position,len,"xxx");
将串stringpos开始的位置,len长度的串由串xxx替代;
code:
<span style="font-size:18px;">#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string replace[7][2] = {
{ "%", "%25" },
{ " ", "%20" },
{ "!", "%21" },
{ "$", "%24" },
{ "(", "%28" },
{ ")", "%29" },
{ "*", "%2a" }
};
int main()
{
//fstream in("input.txt");
string s;
while (getline(cin,s) && s!="#")
{
for (int i = 0; i < 7; i++)
{
int pos = s.find(replace[i][0]);
while (pos != string::npos)
{
s.replace(pos,1,replace[i][1]);
pos += 2;
pos = s.find(replace[i][0],pos);
}
}
cout << s << endl;
}
//system("pause");
return 0;
}
</span>
本文介绍如何在C++中使用getline、find和replace函数进行文本处理,包括字符串读取、查找和替换操作,适用于文本编辑和数据处理场景。
546

被折叠的 条评论
为什么被折叠?



