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.
CodePudding user response:
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);
}
}
CodePudding user response:
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);
}
CodePudding user response:
**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
}