//替换字符串中指定的字符
//先find该字符,删除元素,最后插入元素
void string_replace(string &st1, char c)
{
string::iterator tmp = find(st1.begin(), st1.end(), c);
while (tmp != st1.end())
{
auto x = st1.erase(tmp);
st1.insert(x, '*');
st1.insert(x, '*');
tmp = find(x, st1.end(), c);
}
}
int main()
{
string st1 = " 12 34 56";
string_replace(st1, ' ');
for_each(st1.begin(), st1.end(), [](char chara) {cout << chara; });
return 0;
}
最后总结一点自己常犯的错误
对于string类对象,使用
泛型算法 find()
时,不可以直接搜索一个string对象
,只能搜索一个char类型对象
。
分析:
这是因为string和容器是一样的,容器对象是一个char类型。而泛型算法find()只能搜索容器对象。
解决方法:
想要搜索string对象,只能使用string内置的函数string.find(),可以查找子串的位置;返回的是下标位置,并不是迭代器,这一点要注意。