使用 Java 中的 Apache Commons 库去除字符串中的前导零


org.apache.commons.lang.StringUtils 类的 stripStart() 方法接受两个字符串,并从第一个字符串的字符串中移除第二个字符串表示的字符集。

使用 Apache 公共库从字符串中移除前导零 -

  • 将以下依赖项添加到您的 pom.xml 文件

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>
  • 获取字符串。

  • 将获得的字符串作为第一个参数,并将一个包含 0 的字符串作为第二个参数传递给 StringUtils 类的 stripStart() 方法。

示例

以下 Java 程序从用户读取一个整数值放入一个字符串,并使用 StringUtils 类的 stripStart() 方法移除其中的前导零。

import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class LeadingZeroesCommons {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String: ");
      String str = sc.nextLine();
      String result = StringUtils.stripStart(str, "0");
      System.out.println(result);
   }
}

输出

Enter a String:
000Hello how are you
Hello how are you

更新于:15-Oct-2019

2K+ 浏览量

开始你的职业生涯

完成课程并获得认证

立即开始
广告
© . All rights reserved.