เมธอด stripStart() ของคลาส org.apache.commons.lang.StringUtils รับสตริงสองตัว และลบชุดตัวอักษรที่แทนโดยสตริงตัวที่สองออกจากสตริงตัวแรก
เพื่อลบศูนย์นำหน้าจากสตริงด้วยไลบรารี Apache Commons −
- เพิ่ม dependency ต่อไปนี้ในไฟล์ pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
- ได้สตริง
- ส่งสตริงที่ได้เป็นพารามิเตอร์แรก และสตริงที่มีแค่ "0" เป็นพารามิเตอร์ที่สอง ให้เมธอด stripStart() ของคลาส StringUtils
ตัวอย่าง
โปรแกรม Java ต่อไปนี้อ่านค่า integer จากผู้ใช้เก็บใน String และลบศูนย์นำหน้าออกโดยใช้เมธอด stripStart() ของคลาส StringUtils
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