How to remove leading zeros from alphanumeric text in effective way (Java)

Here is the solution I found on stackoverflow:

Proposed solution is really cool and short, it is based on regular expressions:

s.replaceFirst("^0+(?!$)", "")

Unfortunately, it is regular expressions based solution. So where you are looking for improving your performance  that’s not the ideal solution. Always in such cases it is better to build own small machine state (when performance matters), so below you can find my version of that:

private static String trimLeadingZeros(String source)
    int length = source.length();

    if (length < 2)
        return source;

    int i;
    for (i = 0; i < length-1; i++)
        char c = source.charAt(i);
        if (c != '0')

    if (i == 0)
        return source;

    return source.substring(i);

It is longer, but works fine and it is faster because you don’t need to do regular expression analyse to find leading zeros.

Small optimizations put into above code:

  • for empty input or input with length equal to 1, return the input
  • during iteration over input, skip the last character
  • if we didn’t find leading zeros, return the input

You could change the String.substring method invocation with your own code to make the performance even better, but for my case that’s enough.


4 thoughts on “How to remove leading zeros from alphanumeric text in effective way (Java)

  1. I’m not sure where you are getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

    1. 1. This is a string and it says leading zeros, so basically it doesn’t mean it’s a number.
      2. Since like I already said, it doesn’t mean it’s number, you can write gdfgdf7gdf7g89d and it will still work.

      Conclusion: It removes only the leading zeros from the string: i.e 00sdf0dsfsdfsdfs324234232 -> sdf0dsfsdfsdfs324234232

  2. Thank you for posting this.

    be careful with using string.replace.First to remove leading Zeros.

    when the string is 12340, the result is 1234. However, your posted code does indeed remove only the leading Zeros.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s