有没有办法在字符串中添加字符?
Is there any way to add char in string?
有字符串 "cdfrcs"
。我想获取字符串 *c*d*f*r*c*s
(在每个符号前添加星号)。我应该怎么做?
您可以使用 regex_replace 在 input
字符串中的每个字符前添加一个星号:
auto result = std::regex_replace(input, std::regex{"(.)"}, "*");
在正则表达式 (.)
中,.
匹配每个字符,并且 ()
在捕获组 1 中捕获它。
替换字符串 *
指定每个捕获的字符 </code> 替换为前面的 <code>*
。
这是 demo.
如果您不想使用正则表达式,可以使用以下方法:
std::string a = "cdfrcs";
std::string b = "";
for(char c : a) {
b += std::string("*") + c;
}
有字符串 "cdfrcs"
。我想获取字符串 *c*d*f*r*c*s
(在每个符号前添加星号)。我应该怎么做?
您可以使用 regex_replace 在 input
字符串中的每个字符前添加一个星号:
auto result = std::regex_replace(input, std::regex{"(.)"}, "*");
在正则表达式 (.)
中,.
匹配每个字符,并且 ()
在捕获组 1 中捕获它。
替换字符串 *
指定每个捕获的字符 </code> 替换为前面的 <code>*
。
这是 demo.
如果您不想使用正则表达式,可以使用以下方法:
std::string a = "cdfrcs";
std::string b = "";
for(char c : a) {
b += std::string("*") + c;
}