如何修复我的编码,刚开始使用字符串

How can I fix my coding, new to using string

本文关键字:字符串 刚开始 何修复 我的 编码      更新时间:2023-10-16

我的任务是获取一条"推文"并通过代码getline(com,tweet(运行它并找到缩写(例如BFF,FTW(并发出相同的"推文",但定义了每个遇到的缩写中的第一个。例如。用户在其中输入了两次带有LOL的句子,代码完成后,第一个LOL应该大声笑出来。输入也限制为 160 个字符。我的代码正在做一些有趣的事情,它会打乱定义和反刍的文本。 大声笑,有趣的变成了:大笑,像这样。

#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;

}

你的位置已经偏离了,因为你在进行任何替换之前就得到了它们。
每个字符串最多执行一次替换。

但是你正走在"复制和粘贴"的道路上,这不是一条好路。

相反,首先编写一个函数,该函数将一个字符串的所有匹配项替换为另一个字符串。

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);

首先搜索缩写出现的位置,然后替换它们。替换第一个缩写后,您之前找到的位置将是错误的。

假设字符串是:LOL BFF。所以lol位置是0,bff位置是4。现在你替换了lol,所以字符串是"大声笑BFF",所以bff位置(4(是错误的,你需要再次搜索它才能得到正确的位置。

要修复它,请将查找移动到 if 之前并替换。

另外要检查搜索是否成功,您应该像location != string::npos一样进行比较。