我已經用loop replace構建了基本結構,在C 中str.replace只是替換單個字串,但是,在某些情況下,我們需要替換所有相同的字串,我的代碼可以編譯成功并且可以輸出到螢屏,但似乎沒有替換成功。
提前致謝
這是我的代碼:
#include <iostream>
#include <fstream>
#include <string>
int main(void)
{
// initialize
std::ofstream fout;
std::ifstream fin;
fout.open("cad.dat");
fout << "C is a Computer Programming Language which is used worldwide, Everyone should learn how to use C" << std::endl;
fin.open("cad.dat");
std::string words;
getline(fin,words);
std::cout << words << std::endl;
while(1)
{
std::string::size_type pos(0);
if (pos = words.find("C") != std::string::npos && words[pos 1] != ' ') //the later one is used to detect the single word "C"
{
words.replace(pos, 1, "C ");
}
else
{
break;
}
}
std::cout << words;
}
uj5u.com熱心網友回復:
您可以通過如下方式簡化您的程式regex:
std::regex f("\\bC\\b");
words = std::regex_replace(words, f, "C "); // replace "C" with "C "
然后就不需要while 回圈,如下面的程式所示:
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
int main(void)
{
// initialize
std::ofstream fout;
std::ifstream fin;
fout.open("cad.dat");
fout << "C is a Computer Programming Language which is used worldwide, Everyone should learn how to use C" << std::endl;
fin.open("cad.dat");
std::string words;
getline(fin,words);
std::cout << words << std::endl;
std::regex f("\\bC\\b");
words = std::regex_replace(words, f, "C "); // replace "C" with "C "
std::cout << words;
}
uj5u.com熱心網友回復:
您需要保存pos并將其用于以下find操作,但您當前將其初始化為0回圈中的每次迭代while。
你可以while用這個替換 while回圈,例如:
for(std::string::size_type pos = 0;
(pos = words.find("C", pos)) != std::string::npos; // start find at pos
pos = 1) // skip last found "C"
{
if(pos 1 == words.size() || words[pos 1] == ' ')
words.replace(pos, 1, "C ");
}
注意:這將替換C以Ctoo結尾的in 單詞,例如首字母縮略詞 likeC2C將變為C2C 。此外,C.不會處理以 結尾的句子。要處理這些情況,您也可以在發現之前添加對字符的檢查,C并在檢查中添加標點符號。
例子:
#include <cctype> // isspace, ispunct
#include <iostream>
#include <string>
int main()
{
std::string words = "C Computer C2C C. I like C, because it's C";
std::cout << words << '\n';
// a lambda to check for space or punctuation characters:
auto checker = [](unsigned char ch) {
return std::isspace(ch) || std::ispunct(ch);
};
for(std::string::size_type pos = 0;
(pos = words.find("C", pos)) != std::string::npos;
pos = 1)
{
if( (pos == 0 || checker(words[pos - 1])) &&
(pos 1 == words.size() || checker(words[pos 1]))
) {
words.replace(pos, 1, "C ");
}
}
std::cout << words << '\n';
}
輸出:
C Computer C2C C. I like C, because it's C
C Computer C2C C . I like C , because it's C
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/351925.html
上一篇:將字串元素分配給變數
下一篇:檢查字串是否包含子字串C
