【发布时间】:2021-04-25 20:07:18
【问题描述】:
有字符串"cdfrcs"。我想得到字符串*c*d*f*r*c*s(在每个符号前添加星号)。我该怎么做?
【问题讨论】:
-
接收到的字符串必须是cdfrcs。问题链接:codeforces.com/problemset/problem/118/A
-
std::string或char*字符串?
有字符串"cdfrcs"。我想得到字符串*c*d*f*r*c*s(在每个符号前添加星号)。我该怎么做?
【问题讨论】:
std::string 或 char* 字符串?
您可以使用regex_replace 在input 字符串中的每个字符前添加一个星号:
auto result = std::regex_replace(input, std::regex{"(.)"}, "*$1");
在正则表达式 (.) 中,. 匹配每个字符,() 在捕获组 1 中捕获它。
替换字符串*$1 指定将每个捕获的字符$1 替换为前面的*。
这是demo。
【讨论】:
s 里面有空格吗?它究竟是如何不起作用的?
如果您不想使用正则表达式,可以使用以下方法:
std::string a = "cdfrcs";
std::string b = "";
for(char c : a) {
b += std::string("*") + c;
}
【讨论】: