如果您想要替換包含該詞語的每個字符串,或者僅使用星號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