我的任务是获取一个"tweet“,并通过代码getline(com,tweet)运行它,找到缩写(例如BFF,FTW),然后输出相同的"tweet”,但要定义每个遇到的缩写中的第一个。例如。用户在其中输入两次LOL语句,第一个LOL应该在代码完成时大声笑出来。输入也有160个字符的限制。我的代码做了一些有趣的事情,它打乱了定义和返回的文本。很好笑的LOL变成了:大声点地笑,就像这样。
#include <iostream>
#include <string>
using namespace std;
int main() {
string tweet;
int lol = 0;
int irl = 0;
int afk = 0;
int nvm = 0;
int bff = 0;
int ftw = 0;
int iirc = 0;
int ttyl = 0;
int imho = 0;
cout << "Enter abbreviation from tweet: \n";
getline(cin,tweet);// Output decoded abbreviation from tweet
tweet.resize(160);
lol = tweet.find("LOL");
irl = tweet.find("IRL");
afk = tweet.find("AFK");
nvm = tweet.find("NVM");
ftw =tweet.find("FTW");
bff = tweet.find("BFF");
iirc = tweet.find("IIRC");
ttyl = tweet.find("TTYL");
imho = tweet.find("IMHO");
if (lol >= 0) {
tweet = tweet.replace(lol, 3, "laughing out loud");
cout << endl;
}
if (irl >= 0 ) {
tweet = tweet.replace(irl, 3, "in real life");
cout << endl;
}
if (afk >= 0) {
tweet = tweet.replace(afk, 3, "away from keyboard");
cout << endl;
}
if (nvm >= 0) {
tweet = tweet.replace(nvm, 3, "never mind");
cout << endl;
}
if (bff >= 0) {
tweet = tweet.replace(bff, 3, "best friends forever");
cout << endl;
}
if (ftw >= 0) {
tweet = tweet.replace(ftw, 3, "for the win");
cout << endl;
}
if (iirc >= 0) {
tweet = tweet.replace(iirc, 4, "if I recall correctly");
cout << endl;
}
if (ttyl >=0) {
tweet = tweet.replace(ttyl, 4, "talk to you later");
cout << endl;
}
if (imho >= 0) {
tweet = tweet.replace(imho, 4, "in my humble opinion");
cout << endl;
}
cout << tweet;
cout << endl;
return 0;}
发布于 2018-08-15 15:41:00
您首先搜索出现缩写的位置,然后替换它们。替换第一个缩写后,您以前找到的位置将是错误的。
假设字符串是:LOL BFF。所以lol的位置是0,bff的位置是4。现在你要替换lol,所以字符串是“laughing out bff”,所以bff的位置(4)是错误的,你需要再次搜索它才能得到正确的位置。
要修复它,请将find移到if和replace之前。
此外,为了检查搜索是否成功,您应该像location != string::npos一样进行比较。
发布于 2018-08-15 15:59:13
你的位置是错的,因为你在做任何替换之前就得到了它们。
您还可以对每个字符串进行最多一个替换。
但你正走在“复制粘贴”的道路上,这不是一条好的道路。
相反,可以从编写一个函数开始,该函数将一个字符串的所有匹配项替换为另一个字符串。
std::string replace_all(std::string text, const std::string& src, const std::string& subst)
{
int pos = text.find(src);
while (pos != std::string::npos)
{
text.replace(pos, src.size(), subst);
pos = text.find(src, pos + subst.size() + 1);
}
return text;
}然后使用一个表和一个循环:
std::map<string, string> table = {{"LOL", "loads of loaves"}, {"BFF", "better fast food"}};
for (const auto& it: table)
tweet = replace_all(tweet, it.first, it.second);https://stackoverflow.com/questions/51854606
复制相似问题