使用 Java 中的 apache commons 库从字符串中删除前导零

javaobject oriented programmingprogramming更新于 2024/2/20 9:16:17

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("输入一个字符串:");
      String str = sc.nextLine();
      String result = StringUtils.stripStart(str, "0");
      System.out.println(result);
   }
}

输出

输入一个字符串:
000Hello how are you
Hello how are you

相关文章


有用资源