Reputation: 1
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
So if I have 8650 it will print 8650, instead if I have 0650 it will print 650.
Upvotes: 0
Views: 43
Reputation: 106
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
}
Upvotes: 0
Reputation: 41
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);
}
Upvotes: 1
Reputation: 13506
You have made things complicated,just use String.startsWith()
and
String.substring()`` can do it
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);
}
}
Upvotes: 1