将数字的子字符串替换为Sum



我有一个字符串,它的形式类似于:

"1111 p1p"

我正在尝试用total替换所有的子字符串:

。"4 p1p"

字符串在被替换之前总是包含1而不包含其他数字。

我最初的想法是使用正则表达式拆分字符串,并将其存储在一个向量中,我可以操作它。但是这也删除了分隔符。

std::string newDes = "1111P1P";
std::vector<std::string> desSplit; 
std::regex re1("[^0-9]");
std::sregex_token_iterator first1{newDes.begin(), newDes.end(), re1, -1}, 
desSplit = {first1, last1};

任何帮助都将非常感激。

单个循环将允许您在O(n)运行时间内完成此操作:

std::string str = "1111P1P";
std::string final;
int running_total = 0;
for(auto ch : str) {
if(ch == '1') { 
running_total++;
continue;
}
if(running_total > 0) { final += std::to_string(running_total); }
final += ch;
running_total = 0;
}
// In case we ended on a '1'
if(running_total > 0) { final += std::to_string(running_total); }

实际操作:https://ideone.com/x1BkHy

试试这样:

std::string newDes = "1111P1P";
size_t start = 0, end, count;
while ((start = newDes.find('1', start)) != std::string::npos)
{
if ((end = newDes.find_first_not_of('1', start+1)) == std::string::npos)
end = newDes.size();
count = end - start;
std::string replacement = std::to_string(count);
newDes.replace(start, count, replacement);
start += replacement.size();
}

在线演示

最新更新