我看到过关于如何在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

当前回答

如果你正在使用Kotlin,这是你唯一需要的代码:

yourString.trimStart('0')

其他回答

你可以用regex替换"^0*(.*)"到"$1"

使用Apache Commons StringUtils类:

StringUtils.strip(String str, String stripChars);

不使用Regex或substring()函数的字符串将是低效的-

public static String removeZero(String str){
        StringBuffer sb = new StringBuffer(str);
        while (sb.length()>1 && sb.charAt(0) == '0')
            sb.deleteCharAt(0);
        return sb.toString();  // return in String
    }

按照前面提到的Apache Commons的答案:使用guava-libraries(谷歌的通用Java实用程序库,我认为现在应该在任何非平凡Java项目的类路径上),这将使用CharMatcher:

CharMatcher.is('0').trimLeadingFrom(inputString);

用这个:

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