简体   繁体   English

从字符串中的多个数字中删除前导零? [C ++]

[英]Remove leading zeros from multiple numbers in string? [C++]

Let's say I have a string that contains "00001234 00002345", but I want to output it at "1234 2345". 假设我有一个包含“ 00001234 00002345”的字符串,但我想将其输出为“ 1234 2345”。 How would I go about that? 我将如何处理?

    str.erase(0, str.find_first_not_of('0'));

This removes the 0's from the first number, but not any preceding number. 这将从第一个数字中删除0,但不会删除任何先前的数字。

You can use a \\b0+ regex (it matches 0 symbols after a non-word character, ie [a-zA-Z0-9_] ) if you are interested in a regex solution: 如果您对正则表达式解决方案感兴趣,则可以使用\\b0+正则表达式(它在非单词字符后匹配0符号,即[a-zA-Z0-9_] ):

std::string input("00001234 00002345");
std::regex rgx(R"(\b0+)");
std::cout << std::regex_replace(input, rgx, "");
// => 1234 2345

See IDEONE demo IDEONE演示

Note that raw string literals allow us to use single backslashes to escape regex metacharacters. 请注意,原始字符串文字允许我们使用单个反斜杠来转义正则表达式元字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM