如何修复我的编码,刚开始使用字符串
How can I fix my coding, new to using string
我的任务是获取一条"推文"并通过代码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
一样进行比较。
相关文章:
- 从末尾开始的字符串中获取反向子字符串
- 我如何使它,无论用户用空白字符串按 Enter 多少次,它总是打印"开始"字符串?
- 如何修复我的编码,刚开始使用字符串
- 刚开始学习C++
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- 尝试查找从索引 0 开始的偶数长度子字符串
- 如何从字符串中间开始的子字符串
- 在字符串开始时删除某些字符
- 当给定一个字符串时,Cout 在行首开始打印
- c 字符串开始时ASCII值是什么
- 在我关闭刚开始的孩子对话框并进入父母对话框之后,我的QT桌面应用程序不断崩溃
- 刚开始编码C
- c++ UTF-8 字符串 erro 从 10xxx 开始,带有 cpprestsdk
- 在匹配另一个模式的字符串中找到最短子字符串的开始和结尾索引
- 如何将SSCANF()设置为在字符串开始时忽略字符
- std::字符串在开始和结束之间替换
- 替换字符,如替换全部(字符串,开始,结束,"_","-")
- 如何分辨 boost::split_iterator 从字符串中间开始
- 我刚开始使用特征矩阵代数库,目的是创建一个数据集的相似矩阵,建议
- Std::regex,匹配字符串的开始/结束