解释如何在 Java 中去除字符串开头的零
无论何时将整数值读入字符串,都可以使用**StringBuffer**类、正则表达式或将给定字符串转换为字符数组来去除其开头的零。
转换为字符数组
以下 Java 程序从用户那里读取一个整数值到一个字符串中,并通过将给定的字符串转换为字符数组来去除其开头的零。
示例
import java.util.Scanner;
public class LeadingZeroes {
public static String removeLeadingZeroes(String num){
int i=0;
char charArray[] = num.toCharArray();
for( ; i<= charArray.length; i++){
if(charArray[i] != '0'){
break;
}
}
return (i == 0) ? num :num.substring(i);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroes.removeLeadingZeroes(num);
System.out.println(result);
}
}输出
Enter an integer value as a String 00126718 126718
使用 StringBuffer 类
以下 Java 程序从用户那里读取一个整数值到一个字符串中,并使用 StringBuffer 类去除其开头的零。
示例
import java.util.Scanner;
public class LeadingZeroesSB {
public static String removeLeadingZeroes(String num){
int i=0;
StringBuffer buffer = new StringBuffer(num);
while(i<num.length() && num.charAt(i)=='0')
i++;
buffer.replace(0, i, "");
return buffer.toString();
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesSB.removeLeadingZeroes(num);
System.out.println(result);
}
}输出
Enter an integer: 00012320002 12320002
使用正则表达式
以下 Java 程序从用户那里读取一个整数值到一个字符串中,并使用正则表达式去除其开头的零。
示例
import java.util.Scanner;
public class LeadingZeroesRE {
public static String removeLeadingZeroes(String str){
String strPattern = "^0+(?!$)";
str = str.replaceAll(strPattern, "");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = TailingZeroesRE.removeLeadingZeroes(num);
System.out.println(result);
}
}输出
Enter an integer: 000012336000 12336000
使用 apache commons 库
将以下依赖项添加到你的 pom.xml 文件中
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
以下 Java 程序从用户那里读取一个整数值到一个字符串中,并使用 StringUtils 类的**stripStart()**方法去除其开头的零。
示例
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class LeadingZeroesCommons {
public static String removeLeadingZeroes(String str){
str = StringUtils.stripStart(str, "0");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesCommons.removeLeadingZeroes(num);
System.out.println(result);
}
}输出
Enter an integer: 000125004587 125004587
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP