[英]Is there anyway to delete a specified character in a string?
This is my code这是我的代码
public class StringTest {
public static void main(String []args) {
String str= "8650";
StringBuilder build = new StringBuilder(str);
char index = str.charAt(0);
System.out.println(index+"");
int indexStr= build.indexOf(index+"");
System.out.println(indexStr);
for( int i = 0; i < str.length(); i++) {
if(indexStr == 0)
build.deleteCharAt(indexStr);
}
System.out.println(build);
}
}
I want to delete thé first number if it's 0如果第一个数字是 0,我想删除它
So if I have 8650 it will print 8650, instead if I have 0650 it will print 650.因此,如果我有 8650,它将打印 8650,如果我有 0650,它将打印 650。
You have made things complicated,just use String.startsWith()
and你让事情变得复杂,只需使用String.startsWith()
和
String.substring()`` can do it String.substring()`` 可以做到
public class StringTest {
public static void main(String[] args) {
String str = "8650";
str = "0650";
if (str.startsWith("0")) {
str = str.substring(1);
}
System.out.println(str);
}
}
Below code might help you.下面的代码可能对你有帮助。
public static void main(String[] args) {
String val = "10456";
val = (val.charAt(0) == '0') ? val.substring(1, val.length()) : val;
System.out.println(val);
}
It will remove all leading zero.它将删除所有前导零。
public static void main(String[] args) {
String str = "000650";
str = str.replaceFirst("^0*", "");
System.out.println(str); // output 650 it will remove all leading zero
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.