使用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()方法从用户将一个整数值读取到String中,并从其中删除前导零。

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