我看到过关于如何在SO中加上0前缀的问题。但不是相反!

你们能建议我如何去掉字母数字文本中的前导零吗?是否有任何内置api,或者我需要写一个方法来修剪前导零?

例子:

01234 converts to 1234
0001234a converts to 1234a
001234-a converts to 1234-a
101234 remains as 101234
2509398 remains as 2509398
123z remains as 123z
000002829839 converts to 2829839

当前回答

如果您不想使用正则表达式或外部库。 你可以用“for”:

String input="0000008008451"
String output = input.trim();
for( ;output.length() > 1 && output.charAt(0) == '0'; output = output.substring(1));

System.out.println(output);//8008451

其他回答

使用regex作为一些答案建议是一个很好的方法。如果你不想使用regex,你可以使用下面的代码:

String s = "00a0a121";

while(s.length()>0 && s.charAt(0)=='0')
{
   s = s.substring(1); 
}

如果只搜索第一个非零字符呢?

[1-9]\d+

这个正则表达式查找1到9之间的第一个数字,后面跟着任意数量的数字,因此对于“00012345”,它返回“12345”。 它可以很容易地适应字母数字字符串。

使用Apache Commons StringUtils类:

StringUtils.strip(String str, String stripChars);

用这个:

String x = "00123".replaceAll("^0*", ""); // -> 123

我做了一些基准测试,发现(到目前为止)最快的方法是这个解决方案:

    private static String removeLeadingZeros(String s) {
      try {
          Integer intVal = Integer.parseInt(s);
          s = intVal.toString();
      } catch (Exception ex) {
          // whatever
      }
      return s;
    }

特别是正则表达式在长时间迭代中非常缓慢。(我需要找出批量生产最快的方法。)