- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Leading Zeros From String in Java
There are many approaches to remove leading zeroes from a string in Java. Here we will use some basic functions of String and Arrays class which to remove leading zeroes from a string.
So this approach proceed as first convert string to a character array so that evaluation of each character in string becomes simpler. Now it seems simple that compare each character and find first non zero characters. But here is a constraint that in Java that array doesn't have equals method to compare its value so here we will use valueOf() method of String class to compare each character.
Now we get the position of first non zero digit in our String the only thing remaining is to trim our array upto first non zero digit position. For this use copyOfRange() method which takes three arguments one is original array second is from a position where a copy is to be started and third is to position upto which copy is to be done.
Example
public class RemoveLeadingZeroes { public static void main(String[] args) { String str = "00099898979"; int arrayLength = 0; char[] array = str.toCharArray(); arrayLength = array.length; int firstNonZeroAt = 0; for(int i=0; i<array.length; i++) { if(!String.valueOf(array[i]).equalsIgnoreCase("0")) { firstNonZeroAt = i; break; } } System.out.println("first non zero digit at : " +firstNonZeroAt); char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,arrayLength); String resultString = new String(newArray); System.out.println(resultString); } }
Output
myCSV.csv file created with following text
first non zero digit at : 3 99898979