あなたはstring::replace
とともに、アスタリスク、for_each
とstring::find
との用語、または単に用語を含むすべての文字列を置き換えるために探している場合は良い組み合わせです。
#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
}
この出力:それはより良いあなたに合った場合ラムダは、通常の関数のアドレスに置き換えることができ
*** ***tle Hello
:
*** ****** Hello
にREPLACE_WORD
REPLACE_TERM
に結果を変更する一方。
[string :: find()](http://www.cplusplus.com/reference/string/string/find/)を試してください。文字列内の検索語のインスタンスを検索します。 – chris
ありがとうございます。私は最後の数時間以上これを私に髪を引っ張ってきた! – MacKey
こんにちはクリス、私はupvoteをクリックすると、新しいメンバーとして、それは私が15の評判を必要と述べている!私はそれをどのように克服することができますか? – MacKey