Reputation: 59
I am using this to remove leading zeros from my input string.
return a.replaceAll("^0+","");
But the above string even removes from any string which is alphanumeric as well. I do not want to do that. My requirement is:
Only the leading zeros of numeric numbers should be removed e.g.
00002827393 -> 2827393
If you have a alpha numeric number the leading zeros must not be removed e.g.
000ZZ12340 -> 000ZZ12340
Upvotes: 5
Views: 31291
Reputation: 7466
You can check if your string is only composed of digits first :
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(a);
if(m.matches()){
return a.replaceAll("^0+", "");
} else {
return a;
}
Also :
Upvotes: 10
Reputation: 3142
Simply I did the following
String string = string.trim();
while(string.charAt(0) == '0'){
string = string.substring(1);
}
Upvotes: 0
Reputation: 14278
Logic: it will convert the string to char array and start from i=0; As soon as it hits the first the first numeric value it breaks from the for loop and as soon as it hits first character (other than 1 to 9) it returns the same string. After the first for loop we have following cases to consider:
case 1. 00000000000
case 2. 00000011111
case 3. 11111111111
if it's 1 or 3 (i.e. the i's value from the first for loop will be 0 or length of the string )case then just return the string. Else for the 2nd case copy from the char array to a new char array starting for the i's value (i's value we will get from the first for loop and it holds the first numeric value position.). Hope it clears.
public String trimLeadingZeros(String str)
{
if (str == null)
{
return null; //if null return null
}
char[] c = str.toCharArray();
int i = 0;
for(; i<c.length; i++)
{
if(c[i]=='0')
{
continue;
}
else if(c[i]>='1' && c[i]<='9')
{
break;
}
else
{
return str;
}
}
if(i==0 || i==c.length)
{
return str;
}
else
{
char[] temp = new char[c.length-i];
int index = 0;
for(int j=i; j<c.length; j++)
{
temp[index++] = c[j];
}
return new String(temp);
}
}
Upvotes: 0
Reputation: 129497
You can also try this:
a.replaceAll("^0+(?=\\d+$)", "")
Notice that the positive lookahead (?=\\d+$)
checks to see that the rest of the string (after the starting 0
s, matched by ^0+
) is composed of only digits before matching/replacing anything.
System.out.println("00002827393".replaceAll("^0+(?=\\d+$)", ""));
System.out.println("000ZZ12340".replaceAll("^0+(?=\\d+$)", ""));
2827393 000ZZ12340
Upvotes: 7
Reputation: 178253
Test if the incoming string matches the numeric pattern "\d+". "\d" is the character class for digits. If it's numeric, then return the result of the call to replaceAll
, else just return the original string.
if (str.matches("\\d+"))
return str.replaceAll("^0+", "");
return str;
Testing:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(replaceNumZeroes("0002827393"));
System.out.println(replaceNumZeroes("000ZZ1234566"));
}
yields the output
2827393
000ZZ1234566
Upvotes: 4