删除Java中的前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32253935/
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-11 12:13:19  来源:igfitidea点击:

Remove leading zero in Java

javastring

提问by DataJ

public static String removeLeadingZeroes(String value):

Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”

给定一个有效的非空输入,该方法应返回删除所有前导零的输入。因此,如果输入为“0003605”,则该方法应返回“3605”。作为一种特殊情况,当输入仅包含零(例如“000”或“0000000”)时,该方法应返回“0”

public class NumberSystemService {
/**
 * 
 * Precondition: value is purely numeric
 * @param value
 * @return the value with leading zeroes removed.
 * Should return "0" for input being "" or containing all zeroes
 */
public static String removeLeadingZeroes(String value) {
     while (value.indexOf("0")==0)
         value = value.substring(1);
          return value;
}

I don't know how to write codes for a string "0000".

我不知道如何为字符串“0000”编写代码。

采纳答案by John C

I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)

我会考虑先检查这种情况。逐字符循环遍历字符串,检查非“0”字符。如果您看到非“0”字符,请使用您拥有的过程。如果不这样做,则返回“0”。这是我的方法(未经测试,但已关闭)

boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
    if (value.charAt(i)!='0')
        allZero = false;
}
if (allZero)
    return "0"
...The code you already have

回答by Mureinik

You could add a check on the string's length:

您可以添加对字符串长度的检查:

public static String removeLeadingZeroes(String value) {
     while (value.length() > 1 && value.indexOf("0")==0)
         value = value.substring(1);
         return value;
}

回答by Syam S

If the string always contains a valid integer the return new Integer(value).toString();is the easiest.

如果字符串始终包含有效整数,return new Integer(value).toString();则这是最简单的。

public static String removeLeadingZeroes(String value) {
     return new Integer(value).toString();
}

回答by Anand Kulkarni

You can use pattern matcher to check for strings with only zeros.

您可以使用模式匹配器来检查只有零的字符串。

public static String removeLeadingZeroes(String value) {
    if (Pattern.matches("[0]+", value)) {
        return "0";
    } else {
        while (value.indexOf("0") == 0) {
            value = value.substring(1);
        }
        return value;
    }
}

回答by anirban.at.web

You can try this:
1. If the numeric value of the string is 0 then return new String("0").
2. Else remove the zeros from the string and return the substring.

您可以尝试这样做:
1. 如果字符串的数值为 0,则返回 new String("0")
2. 否则从字符串中删除零并返回子字符串

public static String removeLeadingZeroes(String str)
{
    if(Double.parseDouble(str)==0)
        return new String("0");
    else
    {
        int i=0;
        for(i=0; i<str.length(); i++)
        {
            if(str.charAt(i)!='0')
                break;
        }
        return str.substring(i, str.length());
    }
}

回答by Samarth Urs

private String trimLeadingZeroes(inputStringWithZeroes){
    final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
    return trimZeroes.toString();
}

回答by tfarooqi

Use String.replaceAll(), like this:

使用 String.replaceAll(),像这样:

    public String replaceLeadingZeros(String s) {
        s = s.replaceAll("^[0]+", "");
        if (s.equals("")) {
            return "0";
        }

        return s;
    }

This will match all leading zeros (using regex ^[0]+) and replace them all with blanks. In the end if you're only left with a blank string, return "0" instead.

这将匹配所有前导零(使用正则表达式 ^[0]+)并将它们全部替换为空格。最后,如果您只剩下一个空白字符串,请改为返回“0”。

回答by Aman Systematix

You can use below replace function it will work on a string having both alphanumeric or numeric

您可以使用下面的替换函数,它可以处理具有字母数字或数字的字符串

s.replaceFirst("^0+(?!$)", "")

回答by DwB

  1. Stop reinventing the wheel. Almost no software development problem you ever encounter will be the first time it has been encountered; instead, it will only be the first time you encounter it.
  2. Almost everything utility method you ever need has already been written by the Apache project and/or the guava project.
  3. Read the Apache StringUtils JavaDoc page. This utility is likely to already provide every string manipulation functionality you will ever need
  1. 停止重新发明轮子。您遇到的几乎所有软件开发问题都不会是第一次遇到;相反,它只会是您第一次遇到它。
  2. Apache 项目和/或 guava 项目几乎已经编写了您需要的几乎所有实用程序方法。
  3. 阅读Apache StringUtils JavaDoc 页面。此实用程序可能已经提供了您将需要的所有字符串操作功能

Some example code to solve your problem:

一些示例代码来解决您的问题:

public String stripLeadingZeros(final String data)
{
    final String strippedData;

    strippedData = StringUtils.stripStart(data, "0");

    return StringUtils.defaultString(strippedData, "0");
}

回答by Ketan Ramani

public String removeLeadingZeros(String digits) {
    //String.format("%.0f", Double.parseDouble(digits)) //Alternate Solution
    String regex = "^0+";
    return digits.replaceAll(regex, "");
}

removeLeadingZeros("0123"); //Result -> 123
removeLeadingZeros("00000456"); //Result -> 456
removeLeadingZeros("000102030"); //Result -> 102030