Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing leading zero in java code

Tags:

java

May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools

"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");` 

but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.

Part of My Java code

public String proc_MODEL(Element recElement)
{
 String SEAT        = "";
    try
    {
        SEAT    = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500

       if (SEAT.length()>0)  
       {
           SEAT = SEAT.replaceFirst("^0*", "");  //I need to remove leading zero to only 500 
       }
       catch (Exception e)
       {
           e.printStackTrace();
           return "501 Exception in proc_MODEL";
       }
    } 
}

Appreciate for help.

like image 938
user3835327 Avatar asked Dec 01 '22 01:12

user3835327


2 Answers

If you want remove leading zeros, you could parse to an Integer and convert back to a String with one line like

String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);

Output is

1

Of course if you intend to use the value it's probably better to keep the int

int s = Integer.parseInt(seat);
System.out.println(s);   
like image 187
Elliott Frisch Avatar answered Dec 05 '22 12:12

Elliott Frisch


replaceFirst() was introduced in 1.4 and your compiler pre-dates that.

One possibility is to use something like:

public class testprog {
    public static void main(String[] args) {
        String s = "0001000";
        while ((s.length() > 1) && (s.charAt(0) == '0'))
            s = s.substring(1);
        System.out.println(s);
    }
}

It's not the most efficient code in the world but it'll get the job done.

A more efficient segment without unnecessary string creation could be:

public class testprog {
    public static void main(String[] args) {
        String s = "0001000";
        int pos = 0;
        int len = s.length();
        while ((pos < len-1) && (s.charAt(pos) == '0'))
            pos++;
        s = s.substring(pos);
        System.out.println(s);
    }
}

Both of those also handle the degenerate cases of an empty string and a string containing only 0 characters.

like image 26
paxdiablo Avatar answered Dec 05 '22 14:12

paxdiablo