[英]How can I fix my coding, new to using string
我的任務是獲取一個“ tweet”,並通過代碼getline(com,tweet)運行它,並找到縮寫(例如BFF,FTW),並發出相同的“ tweet”,但首先定義每個遇到的縮寫。 例如。 用戶在其中輸入了兩次帶有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;
}
您首先搜索縮寫出現的位置,然后替換它們。 替換第一個縮寫后,您先前找到的位置將是錯誤的。
說的字符串是: LOL BFF
。 因此,lol的位置為0,bff的位置為4。現在您替換lol,因此字符串是“大聲笑出BFF”,因此bff的位置(4)是錯誤的,您需要再次搜索以獲取正確的位置。
要解決此問題,請將查找結果移動到if和replace之前。
另外要檢查搜索是否成功,您應該像location != string::npos
進行比較。
您的職位不正確,因為您在進行任何替換之前都獲得了這些職位。
每個字符串最多也要進行一次替換。
但是,您正在走“復制粘貼”的道路,這不是一個好的路徑。
相反,首先要編寫一個函數,用一個字符串替換所有出現的字符串。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.