C++ 如何用新词替换未知数量的相同字符?
我想做的是如果我有一根像C++ 如何用新词替换未知数量的相同字符?,c++,C++,我想做的是如果我有一根像 std::string test=“2xs***gcv”是否有可能以某种方式用新词e.x替换星号的所有实例。问题是*的数量并不总是3,可能是5、7、2等等,但它们总是在一起 到目前为止,我得到的是 std::string test=“2xs***gcv” char*pos; pos=strchr(result.c_str(),'*'); while(pos!=NULL){ printf(“在%d\n处找到”,pos result.c_str()+1); pos=strc
std::string test=“2xs***gcv”
是否有可能以某种方式用新词e.x替换星号的所有实例。问题是*的数量并不总是3,可能是5、7、2等等,但它们总是在一起
到目前为止,我得到的是
std::string test=“2xs***gcv”
char*pos;
pos=strchr(result.c_str(),'*');
while(pos!=NULL){
printf(“在%d\n处找到”,pos result.c_str()+1);
pos=strchr(pos+1,'*');
}
它告诉我*的位置,问题是我似乎不知道如何仅隔离*的第一个实例和最后一个实例。
std::string
既有find
又有rfind
,因此如果您知道字符串将只包含一组连续的星号,您可以找到它们的开头和结尾,如下所示:
auto left = test.find('*');
auto right = test.rfind('*');
test.replace(left, right-left+1, "WORD");
然后,您可以将该范围替换为一些新数据,如下所示:
auto left = test.find('*');
auto right = test.rfind('*');
test.replace(left, right-left+1, "WORD");
像往常一样,为了简单/清晰,我省略了任何错误检查(以及类似的检查)。
std::string
同时具有find
和rfind
,因此如果您知道字符串将只包含一组连续的星号,您可以找到它们的开头和结尾,如下所示:
auto left = test.find('*');
auto right = test.rfind('*');
test.replace(left, right-left+1, "WORD");
然后,您可以将该范围替换为一些新数据,如下所示:
auto left = test.find('*');
auto right = test.rfind('*');
test.replace(left, right-left+1, "WORD");
像往常一样,为了简单/清晰,我省略了任何错误检查(等等)。您可以使用正则表达式。@eerorika好主意,甚至没有想过,要试试看!谢谢。你可以用正则表达式。@eerorika好主意,没想过,我要试试!谢谢。还有
std::string::find_first_not_of()
:auto right=test.find_first_not_of(“*”,left+1)代码>还有std::string::find_first_not_of()
:auto right=test.find_first_not_of(“*”,left+1)代码>