简体   繁体   English

删除Java中的前导零

[英]Remove leading zero in Java

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”.因此,如果输入为“0003605”,则该方法应返回“3605”。 As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”作为一种特殊情况,当输入仅包含零(例如“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”编写代码。

If the string always contains a valid integer the return new Integer(value).toString();如果字符串始终包含有效整数,则return new Integer(value).toString(); is the easiest.是最简单的。

public static String removeLeadingZeroes(String value) {
     return new Integer(value).toString();
}
  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 every utility method you will ever need has already been written by the Apache project and/or the guava project (or some similar that I have not encountered). Apache 项目和/或 guava 项目(或一些我没有遇到过的类似项目)已经编写了您需要的几乎所有实用方法。
  3. Read the Apache StringUtils JavaDoc page .阅读Apache StringUtils JavaDoc 页面 This utility is likely to already provide every string manipulation functionality you will ever need.此实用程序可能已经提供了您需要的所有字符串操作功能。

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");
}

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;
}

I would consider checking for that case first.我会考虑先检查这种情况。 Loop through the string character by character checking for a non "0" character.逐字符循环遍历字符串,检查非“0”字符。 If you see a non "0" character use the process you have.如果您看到非“0”字符,请使用您拥有的过程。 If you don't, return "0".如果不这样做,则返回“0”。 Here's how I would do it (untested, but close)这是我的方法(未经测试,但已关闭)

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
private String trimLeadingZeroes(inputStringWithZeroes){
    final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
    return trimZeroes.toString();
}

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

s.replaceFirst("^0+(?!$)", "")
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

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;
    }
}

You can try this:你可以试试这个:
1. If the numeric value of the string is 0 then return new String("0") . 1. 如果字符串的数值为 0,则返回 new String("0")
2. Else remove the zeros from the string and return the substring . 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());
    }
}

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.这将匹配所有前导零(使用正则表达式 ^[0]+)并将它们全部替换为空格。 In the end if you're only left with a blank string, return "0" instead.最后,如果您只剩下一个空白字符串,请改为返回“0”。

int n = 000012345;
n = Integer.valueOf(n + "", 10);

It is important to specify radix 10, else the integer is read as an octal literal and an incorrect value is returned.指定基数 10 很重要,否则整数将被读取为八进制文字并返回不正确的值。

public String removeLeadingZeros(String num) {
    String res = num.replaceAll("^0+", "").trim();
    return res.equals("")? "0" : res;
}
  1. Convert input to StringBuilder将输入转换为StringBuilder

  2. Use deleteCharAt method to remove character from beginning till non-zero character is found使用deleteCharAt方法从头开始删除字符直到找到非零字符

    String trimZero(String str) { StringBuilder strB = new StringBuilder(str); int index = 0; while (strB.length() > 0 && strB.charAt(index) == '0') { strB.deleteCharAt(index); } return strB.toString(); }

I have found the following to be the simplest and most reliable, as it works for both integers and floating-point numbers:我发现以下是最简单和最可靠的,因为它适用于整数和浮点数:

public static String removeNonRequiredLeadingZeros(final String str) {
    return new BigDecimal(str).toPlainString();
}

You probably want to check the incoming string for null and blank, and also trim it to remove leading and trailing whitespace.您可能想要检查传入的字符串是否为空和空白,并修剪它以删除前导和尾随空格。

You can also get rid of trailing zeros by using:您还可以使用以下方法去除尾随零:

public static String removeNonRequiredZeros(final String str) {
    return new BigDecimal(str).stripTrailingZeros().toPlainString();
}

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

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