删除Java中的前导零

Dat*_*taJ 7 java string

public static String removeLeadingZeroes(String value):
Run Code Online (Sandbox Code Playgroud)

给定有效的非空输入,该方法应返回所有前导零被删除的输入.因此,如果输入是"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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何为字符串"0000"编写代码.

Sya*_*m S 32

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

public static String removeLeadingZeroes(String value) {
     return new Integer(value).toString();
}
Run Code Online (Sandbox Code Playgroud)


DwB*_*DwB 5

  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");
}
Run Code Online (Sandbox Code Playgroud)


小智 1

我会考虑先检查一下这个案例。逐个字符地循环遍历字符串,检查是否有非“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
Run Code Online (Sandbox Code Playgroud)