如果您想要替换包含该词语的每个字符串,或者仅使用星号for_each
和string::find
以及string::replace
是一个很好的组合。
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <algorithm> //for_each
#define REPLACE_WORD
int main()
{
vector<string> testlist (3); //your file
testlist [0] = "bat";
testlist [1] = "battle";
testlist [2] = "Hello";
string searchTerm = "bat";
for_each (testlist.begin(), testlist.end(), //iterate through vector
[&](string &word) { //calling this lambda for each
#ifdef REPLACE_WORD //replacing whole word
if (word.find (searchTerm) != string::npos) //if term is found
word.replace (0, word.length(), word.length(), '*'); //replace starting at char 0 for length() chars, with length() *s
#else //REPLACE_TERM
if (word.find (searchTerm) != string::npos)
word.replace (word.find (searchTerm), searchTerm.length(), searchTerm.length(), '*'); //same, but start at where it finds the term, and only replace that
#endif
} //end lambda
); //end for_each
for_each (testlist.begin(), testlist.end(), [](string word){cout << word << ' ';}); //output vector
}
此输出:
*** ****** Hello
而改变REPLACE_WORD
到REPLACE_TERM
结果:
*** ***tle Hello
拉姆达可以用普通的函数地址,如果它适合你更好的进行更换。
尝试[string :: find()](http://www.cplusplus.com/reference/string/string/find/)。它将在字符串中查找搜索项的任何实例。 – chris 2012-03-22 01:04:50
谢谢。在过去的几个小时里,我一直在拉我的头发! – MacKey 2012-03-22 01:16:28
嗨克里斯,作为新成员,当我点击upvote时,它声明我需要15个声望!不能看我怎么能超越那个! – MacKey 2012-03-22 14:51:04