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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25726531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:25:00  来源:igfitidea点击:

How to remove leading zeros from string using C++?

c++string

提问by samio peter

I want to remove leading zeroes from string like "0000000057".

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

I did like this but didn't get any result:

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

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

string p48Z03 = AccProcPeriNum.substr(3, 10);

I want output only 57.

我只想要输出57

Any idea in C++?

在 C++ 中有什么想法吗?

回答by intijk

Piotr S's answer is good but there is one case it will return wrong answer, that is the all zero case:

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

000000000000

000000000000

To consider this in, use:

要考虑这一点,请使用:

str.erase(0, min(str.find_first_not_of('0'), str.size()-1));

Even you str.size() be 0, it will also work.

即使你的 str.size() 为 0,它也能工作。

回答by Piotr Skotnicki

#include <string>    

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

assert(str == "57");

LIVE DEMO

LIVE DEMO

回答by Jerry Coffin

Although it's probably notthe most efficient (in terms of run-time speed) way to do things, I'd be tempted to just do something like:

尽管这可能不是最有效的(就运行时速度而言)做事的方式,但我很想这样做:

std::cout << std::stoi(strCustData);

This is simple and straightforward to use, and gives a reasonable output (a single '0') when the input consists entirely of 0s. Only when/if profiling showed that this simple solution was a problem would I consider writing substantially more complex code in the hopes of improving speed (and I doubt that would arise).

这使用起来简单直接,并且在输入完全由0s组成时给出了合理的输出(单个“0”)。只有当/如果分析表明这个简单的解决方案是一个问题,我才会考虑编写更复杂的代码以希望提高速度(我怀疑会出现这种情况)。

The obvious limitation here is that this does assume that the characters after the leading zeros are digits. That's clearly true in your sample, but I suppose it's conceivable that you have data where it's not true.

这里明显的限制是,这确实假设前导零后面的字符是数字。这在您的样本中显然是正确的,但我想可以想象您拥有不正确的数据。

回答by cdhowie

This should work as a generic function that can be applied to any of the std::basic_stringtypes (including std::string):

这应该作为可以应用于任何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();
}

In your case you would use it like this:

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

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

// trimmed is now "57"

(See a demo.)

见演示。)

回答by Mohit Jawale

#include<algorithm>
#include<iostream>
#include<string>
using namespace std;


int main()
{
   string s="00000001";
   cout<<s<<endl;
   int a=stoi(s);
   cout<<a;
   //1 is ur ans zeros are removed


}

回答by Yoga

This C language friendly code removes leading zeros and can be used as long as the char array's length fits within an int:

这个 C 语言友好的代码删除了前导零,只要字符数组的长度在一个范围内就可以使用int

char charArray[6] = "000342";
int inputLen = 6;

void stripLeadingZeros() {
    int firstNonZeroDigitAt=0, inputLen = strlen(charArray);

    //find location of first non-zero digit, if any
    while(charArray[firstNonZeroDigitAt] == '0')
        firstNonZeroDigitAt++;

    //string has no leading zeros
    if(firstNonZeroDigitAt==0)
        return; 

    // string is all zeros
    if(firstNonZeroDigitAt==inputLen) {
        memset(charArray, 0, sizeof charArray);
        strcpy(charArray, "0");
        inputLen = 1;
        return;
    }

    //shift the non-zero characters down
    for(int j=0; j<inputLen-firstNonZeroDigitAt; j++) {
        charArray[j] = charArray[firstNonZeroDigitAt+j];
    }

    //clear the occupied area and update string length
    memset(charArray+inputLen-firstNonZeroDigitAt, 0, inputLen-firstNonZeroDigitAt+1);
    inputLen -= firstNonZeroDigitAt;
}