308

I've seen questions on how to prefix zeros here in SO. But not the other way!

Can you guys suggest me how to remove the leading zeros in alphanumeric text? Are there any built-in APIs or do I need to write a method to trim the leading zeros?

Example:

01234 converts to 1234
0001234a converts to 1234a
001234-a converts to 1234-a
101234 remains as 101234
2509398 remains as 2509398
123z remains as 123z
000002829839 converts to 2829839
Jonik
  • 80,077
  • 70
  • 264
  • 372
jai
  • 21,519
  • 31
  • 89
  • 120

21 Answers21

756

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

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

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

Test harness:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

See also

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
167

You can use the StringUtils class from Apache Commons Lang like this:

StringUtils.stripStart(yourString,"0");
Hamilton Rodrigues
  • 1,779
  • 1
  • 11
  • 3
40

How about the regex way:

String s = "001234-a";
s = s.replaceFirst ("^0*", "");

The ^ anchors to the start of the string (I'm assuming from context your strings are not multi-line here, otherwise you may need to look into \A for start of input rather than start of line). The 0* means zero or more 0 characters (you could use 0+ as well). The replaceFirst just replaces all those 0 characters at the start with nothing.

And if, like Vadzim, your definition of leading zeros doesn't include turning "0" (or "000" or similar strings) into an empty string (a rational enough expectation), simply put it back if necessary:

String s = "00000000";
s = s.replaceFirst ("^0*", "");
if (s.isEmpty()) s = "0";
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
40

If you are using Kotlin This is the only code that you need:

yourString.trimStart('0')
Saman Sattari
  • 3,322
  • 6
  • 30
  • 46
30

A clear way without any need of regExp and any external libraries.

public static String trimLeadingZeros(String source) {
    for (int i = 0; i < source.length(); ++i) {
        char c = source.charAt(i);
        if (c != '0') {
            return source.substring(i);
        }
    }
    return ""; // or return "0";
}
magiccrafter
  • 5,175
  • 1
  • 56
  • 50
  • 1
    Although your check for space isn't according to the question, nevertheless I think your answer would execute the quickest. – John Fowler Oct 29 '15 at 23:00
  • @JohnFowler 10x for the catch, fixed after 2+ years – magiccrafter Jan 31 '18 at 12:04
  • 1
    And the method needs a return at the end if the loop finds only zeros. return ""; or return "0"; if you want at least one zero – slipperyseal Feb 23 '18 at 00:19
  • @slipperyseal I left it open so that you can change it based on your needs but since people tend to copy/paste, it is not a bad idea to always have a default behaviour. thanks for the comment – magiccrafter Feb 23 '18 at 11:32
15

To go with thelost's Apache Commons answer: using guava-libraries (Google's general-purpose Java utility library which I would argue should now be on the classpath of any non-trivial Java project), this would use CharMatcher:

CharMatcher.is('0').trimLeadingFrom(inputString);
Cowan
  • 37,227
  • 11
  • 66
  • 65
  • +1, the correct answer for any project using Guava. (And now in 2012 that *should* mean pretty much any Java project.) – Jonik May 22 '12 at 09:18
  • 1
    @Cowan Does this have a problem with "0" alone? Will CharMatcher.is('0').trimLeadingFrom("0"); Return the "0" or empty String? – PhoonOne Feb 17 '15 at 17:28
  • @PhoonOne: I just tested this; it returns the empty string. – Stephan202 Dec 14 '16 at 09:48
13

You could just do: String s = Integer.valueOf("0001007").toString();

Kao
  • 7,225
  • 9
  • 41
  • 65
Damjan
  • 139
  • 1
  • 2
6

Use this:

String x = "00123".replaceAll("^0*", ""); // -> 123
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
5

Use Apache Commons StringUtils class:

StringUtils.strip(String str, String stripChars);
Pang
  • 9,564
  • 146
  • 81
  • 122
thelost
  • 6,638
  • 4
  • 28
  • 44
2

Using regex as some of the answers suggest is a good way to do that. If you don't want to use regex then you can use this code:

String s = "00a0a121";

while(s.length()>0 && s.charAt(0)=='0')
{
   s = s.substring(1); 
}
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
  • This could create a lot of `String`... use [magiccrafter approch](https://stackoverflow.com/a/7089841/4391450) instead. – AxelH Jan 12 '18 at 12:06
2

If you (like me) need to remove all the leading zeros from each "word" in a string, you can modify @polygenelubricants' answer to the following:

String s = "003 d0g 00ss 00 0 00";
s.replaceAll("\\b0+(?!\\b)", "");

which results in:

3 d0g ss 0 0 0
xdhmoore
  • 8,935
  • 11
  • 47
  • 90
2

Using kotlin it is easy

value.trimStart('0')
Shaon
  • 2,496
  • 26
  • 27
2

Using Regexp with groups:

Pattern pattern = Pattern.compile("(0*)(.*)");
String result = "";
Matcher matcher = pattern.matcher(content);
if (matcher.matches())
{
      // first group contains 0, second group the remaining characters
      // 000abcd - > 000, abcd
      result = matcher.group(2);
}

return result;
brj
  • 21
  • 1
1

I think that it is so easy to do that. You can just loop over the string from the start and removing zeros until you found a not zero char.

int lastLeadZeroIndex = 0;
for (int i = 0; i < str.length(); i++) {
  char c = str.charAt(i);
  if (c == '0') {
    lastLeadZeroIndex = i;
  } else {
    break;
  }
}

str = str.subString(lastLeadZeroIndex+1, str.length());
Community
  • 1
  • 1
vodkhang
  • 18,639
  • 11
  • 76
  • 110
1

Without using Regex or substring() function on String which will be inefficient -

public static String removeZero(String str){
        StringBuffer sb = new StringBuffer(str);
        while (sb.length()>1 && sb.charAt(0) == '0')
            sb.deleteCharAt(0);
        return sb.toString();  // return in String
    }
Sachin Aggarwal
  • 1,095
  • 8
  • 17
0
       String s="0000000000046457657772752256266542=56256010000085100000";      
    String removeString="";

    for(int i =0;i<s.length();i++){
      if(s.charAt(i)=='0')
        removeString=removeString+"0";
      else 
        break;
    }

    System.out.println("original string - "+s);

    System.out.println("after removing 0's -"+s.replaceFirst(removeString,""));
0

You could replace "^0*(.*)" to "$1" with regex

YOU
  • 120,166
  • 34
  • 186
  • 219
0

If you don't want to use regex or external library. You can do with "for":

String input="0000008008451"
String output = input.trim();
for( ;output.length() > 1 && output.charAt(0) == '0'; output = output.substring(1));

System.out.println(output);//8008451
kfatih
  • 119
  • 1
  • 5
0

I made some benchmark tests and found, that the fastest way (by far) is this solution:

    private static String removeLeadingZeros(String s) {
      try {
          Integer intVal = Integer.parseInt(s);
          s = intVal.toString();
      } catch (Exception ex) {
          // whatever
      }
      return s;
    }

Especially regular expressions are very slow in a long iteration. (I needed to find out the fastest way for a batchjob.)

-2

And what about just searching for the first non-zero character?

[1-9]\d+

This regex finds the first digit between 1 and 9 followed by any number of digits, so for "00012345" it returns "12345". It can be easily adapted for alphanumeric strings.

shas123
  • 27
  • 7
-2

  const removeFirstZero = (ele) => parseInt(ele).toString()
  
  console.log('raw ' + '0776211121')
  console.log('removedZero ' + removeFirstZero('0776211121'))
  • 1
    That does not answer the question, because it does not work if the input contains other characters. – Hulk Mar 30 '23 at 11:24
  • The question was asked about Java (refer to question tags), also the answer expected shall be covering all the cases and not just one particular case. Also, check if the question has been already answered. – shashi009 Apr 01 '23 at 16:01
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 01 '23 at 16:01