【问题标题】:How do I search a string for specific characters and replace them? [duplicate]如何在字符串中搜索特定字符并替换它们? [复制]
【发布时间】:2015-09-25 20:19:24
【问题描述】:

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

基本上我需要在“tweet”中搜索诸如 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;

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

【问题讨论】:

  • 请举例说明输入和输出不能正常工作。
  • @MohitJain,是的,position 目前不反映find 返回的类型。如果是这样,前一个检查总是正确的,如果你问我,这很冒险。
  • @Adrian 老实说,我为此花了几个小时。我发现我认为是一个适当的解决方案,但如上所示,它不起作用。

标签: c++ string search replace


【解决方案1】:

改成

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;

【讨论】:

  • 如果字符串包含不止一次出现的"LOL" 等怎么办?
  • 如果有递归首字母缩写词,比如“PHP”->“PHP:超文本预处理器”怎么办?
猜你喜欢
  • 2011-04-13
  • 2020-07-09
  • 2012-07-08
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多