Using Regular Expressions (regex)
System.out.println("*" + str.replaceFirst("^0+", "") + "*");
//*938*
Suppose the string contains only zeroes, then the output will be a null string.
String str = "0000000";
System.out.println("*" + str.replaceFirst("^0+", "") + "*");
//**
String str = "0000000";
System.out.println("*" + str.replaceFirst("^0+(?!$)", "") + "*");
//*0*
The negative lookahead (?!$) ensures that the entire string is not matched with the regular expression ^0+.
The anchor ^ makes sure that the beginning of the input is matched. 0+ denotes zero or more zeroes (0s).
0 Comments