使用 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+ 瀏覽量

開始你的職業生涯

完成課程並獲得認證

立即開始
廣告