我試圖用來自std::string. 這是我到目前為止嘗試過的:
int main()
{
std::string line = "my name is my name and not my name mysometext myto";
std::string replaceThis,replaceWith;
std::getline(std::cin, replaceThis);
std::getline(std::cin, replaceWith);
size_t pos = line.find(replaceThis);
size_t len = replaceThis.length();
line.replace(pos, len, replaceWith);
std::cout << line << std::endl;
return 0;
}
實際產量
my
your
your name is my name and not my name mysometext myto
如您所見,只有第一次出現的my是 replace with your。我想我可以遍歷每個單詞 ofline然后對每個單詞執行相同操作并替換my為your. 但是有沒有一種內置的方式(比如使用regex)來做到這一點而不是重新發明輪子?
預期產出
my
your
your name is your name and not your name mysometext myto
如上面的預期輸出所示,我想my用your 除其他單詞內的單詞之外的所有單詞替換所有出現的單詞。那是最后,我想要一個除了那些發生在其他詞中的東西之外std::string,所有的東西都被my替換了。your
uj5u.com熱心網友回復:
但是有沒有一種內置的方式(比如使用正則運算式)來做到這一點而不是重新發明輪子?
是的,有一種方法可以做到這一點,regex如下所示:
int main()
{
std::string line{"my name is my name and not my name mysometext myto"}; //this is the original line
std::cout << line << std::endl;
std::string replaceThis,replaceWith;
std::cout<<"Enter the word that you want to replace in the above: ";
std::getline(std::cin, replaceThis);
std::cout<<"Enter the word that you want to replace it with: ";
std::getline(std::cin, replaceWith);
std::regex pattern("\\b" replaceThis "\\b");
std::string replacedLine = std::regex_replace(line, pattern, replaceWith);
std::cout<<replacedLine<<std::endl;
}
上述程式的輸出如下:
my name is my name and not my name mysometext myto
Enter the word that you want to replace in the above: my
Enter the word that you want to replace it with: your
your name is your name and not your name mysometext myto
這也可以在這里看到
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392261.html
上一篇:while回圈應該在讀取我的檔案中的第三行后結束,但為什么它第四次運行?[復制]
下一篇:C 錯誤:“operator[]”不匹配(運算元型別是“constmy_array_over”和“size_t”{aka“longunsignedint”})
