• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

How to strip off zero's from the front of a String

Hi I have an eight char customer ID, it will always be eight characters long

examples
'00054398'
'89700937'
'02329329'

Now what I need is a method which gives a number without the zeroes in the front if I pass the number to that method.

'54398'
'89700937'
'2329329'
Any help will be greatly appreciated
0
royalcyber
Asked:
royalcyber
1 Solution
 
appxpeteCommented:
public static String removeLeadingZeros(String str)
         {
                 if (str == null)
                 {
                         return null;
                 }
                 char[] chars = str.toCharArray();
                 int index = 0;
                 for (; index < str.length(); index++)
                 {
                         if (chars[index] != '0')
                         {
                                 break;
                         }
                 }
                 return (index == 0) ? str : str.substring(index);
         }
0
 
mukundha_expertCommented:
You can also do it this way,

StringBuffer buf = new StringBuffer ( inputString ) ;
while ( buf.charAt( 0 ) == '0') buf.deleteCharAt ( 0 );

String outString = buf.toString () ;

Cheers,
Mukundh
0
 
radarshCommented:
Hi royalcyber,

Try this:

String input = "0003483";
String output = String.valueOf(Long.parseLong(input));

________
radarsh
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
radarshCommented:
Another solution.

String input = "0003483";
String output = input.replaceAll("^0*", "");

________
radarsh
0
 
hoomanvCommented:
nice jobs
appxpete's solution is fast
radarsh's is short

and here is mine

replaceFirst("^0*", "");

I think its faster than replaceAll since it discontinues sooner. is it ?
0
 
radarshCommented:
Yes it is notably faster than replaceAll.

________
radarsh
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now