繁体   English   中英

删除Java中的前导零

[英]Remove leading zero in Java

public static String removeLeadingZeroes(String value):

给定一个有效的非空输入,该方法应返回删除所有前导零的输入。 因此,如果输入为“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;
}

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

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

public static String removeLeadingZeroes(String value) {
     return new Integer(value).toString();
}
  1. 停止重新发明轮子。 您遇到的几乎所有软件开发问题都不会是第一次遇到; 相反,它只会是您第一次遇到它。
  2. Apache 项目和/或 guava 项目(或一些我没有遇到过的类似项目)已经编写了您需要的几乎所有实用方法。
  3. 阅读Apache StringUtils JavaDoc 页面 此实用程序可能已经提供了您需要的所有字符串操作功能。

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

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

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

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

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

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

我会考虑先检查这种情况。 逐字符循环遍历字符串,检查非“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
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

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

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

你可以试试这个:
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());
    }
}

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

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

        return s;
    }

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

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

指定基数 10 很重要,否则整数将被读取为八进制文字并返回不正确的值。

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

  2. 使用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(); }

我发现以下是最简单和最可靠的,因为它适用于整数和浮点数:

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

您可能想要检查传入的字符串是否为空和空白,并修剪它以删除前导和尾随空格。

您还可以使用以下方法去除尾随零:

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