Phương thức stripStart() của org.apache.commons.lang.StringUtils nhận 2 string và xóa tập ký tự của string thứ 2 từ string thứ 1.
Để xóa leading zeros dùng apache commons:
Thêm dependency vào pom.xml:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
Lấy string.
Gọi stripStart() của StringUtils với string làm tham số 1 và "0" làm tham số 2.
Ví dụ
Chương trình đọc integer từ user vào String, xóa leading zeros bằng stripStart() của 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); } }
Kết quả
Enter a String: 000Hello how are you Hello how are you