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.
![enter image description here]()
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);
}
}