如何在字符串中搜索特定字符并替换它们?

时间:2015-07-08 05:07:59

标签: c++ string search replace

嘿,我知道这是一个愚蠢的问题,但我真的需要在我的编程课上完成练习,而且我无法在任何地方找到解决方案。

基本上我需要在“推文”中搜索lol之类的缩写,并用实际单词替换它们。

我已经尝试过这段代码但有时会删除字符串的开头。

string usertweet;
cout << "Please enter a tweet. " << endl; 
cin >> usertweet;

getline(cin, usertweet);
usertweet.resize(160); // Cut down the tweet to 160 chars.

int position; //Used for searching for abrvs.
position = usertweet.find("AFK");
if (position >= 0) {
    usertweet.replace(position,3,"Away from Keyboard");
}

position = usertweet.find("BRB");
if (position >= 0) {
    usertweet.replace(position,3,"Be Right Back");
}

cout << usertweet;

抱歉这个愚蠢的问题,并提前非常感谢你!

1 个答案:

答案 0 :(得分:0)

更改为

string usertweet;
cout << "Please enter a tweet. " << endl; 
cin >> usertweet;

getline(cin, usertweet);
usertweet.resize(160); // Cut down the tweet to 160 chars.

for (size_t p = usertweet.find("AFK"); p != string::npos; p = usertweet.find("AFK", p + 1))
    usertweet.replace(p, 3, "Away from Keyboard");

for (size_t p = usertweet.find("BRB"); p != string::npos; p = usertweet.find("BRB", p + 1))
    usertweet.replace(p, 3, "Be Right Back");

cout << usertweet;