如何使用C++从字符串中删除前导零?

sam*_*ter 11 c++ string

我想从字符串中删除前导零"0000000057".

我确实喜欢这个,但没有得到任何结果:

string AccProcPeriNum = strCustData.substr(pos, 13);

string p48Z03 = AccProcPeriNum.substr(3, 10);
Run Code Online (Sandbox Code Playgroud)

我只想输出57.

用C++的想法?

int*_*ijk 22

Piotr S的答案是好的,但有一种情况它将返回错误的答案,即全零情况:

000000000000

要考虑这一点,请使用:

str.erase(0, min(str.find_first_not_of('0'), str.size()-1));
Run Code Online (Sandbox Code Playgroud)

即使你str.size()为0,它也会工作.


Pio*_*cki 17

#include <string>    

std::string str = "0000000057";
str.erase(0, str.find_first_not_of('0'));

assert(str == "57");
Run Code Online (Sandbox Code Playgroud)

LIVE DEMO

  • 如果 str = "0",它不应该执行任何操作,但您的代码使其成为空字符串 (3认同)

cdh*_*wie 2

这应该作为一个通用函数,可以应用于任何类型std::basic_string(包括std::string):

template <typename T_STR, typename T_CHAR>
T_STR remove_leading(T_STR const & str, T_CHAR c)
{
    auto end = str.end();

    for (auto i = str.begin(); i != end; ++i) {
        if (*i != c) {
            return T_STR(i, end);
        }
    }

    // All characters were leading or the string is empty.
    return T_STR();
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你会像这样使用它:

string x = "0000000057";
string trimmed = remove_leading(x, '0');

// trimmed is now "57"
Run Code Online (Sandbox Code Playgroud)

参见演示。)