简体   繁体   中英

Remove X Character occurence from Starting of string until Different Character Not found in Java

I am stuck in problem and not find Solution please help me to resolve it. Below is code

String number = "000097127073653";

Boolean isOtherDigitFound = false;

int i=0;

for(int x=0 ; x<nunber.toCharArray() ; x++){

    if(number.toChatArray()[x] != 0 && !isOtherDigitFound ){
      isOtherDigitFound=true;
      i=x;
    }
}

number = number.subStr(x,number.length);

System.out.print(number);

I got the output that i wants which is 97127073653 But there is some easy way to do this.

I want to remove all occurence of 0 from Starting of string.but not from middle or somewhere else.

Example:- I have Number like 0000123400022 then output should be like 123400022

Please help me

Thanks in advance

For example, the above code to work may look like this

    String number = "0000123400022";

    Boolean isOtherDigitFound = false;

    int i = 0;
    

    for (int x = 0; x < number.length(); x++) {

        if (number.charAt(x) != '0' && !isOtherDigitFound) {
            isOtherDigitFound = true;
            i = x;
            break;
        }
    }

    number = number.substring(i, number.length());

    System.out.print(number);

You could use replaceAll method in Java's String class.

number = number.replaceAll("^0+", ""));

by adding ^ in replaceAll method replaces the leading characther and by adding $ the trailing characters are replaced. So if you want to replace the trailing 0 values of the string you can do number.replaceAll("0+$", "");

Now you may rewrite your code to simply three lines

String number = "000097127073653";
number = number.replaceAll("^0+", ""));
System.out.print(number);

I'll do it something like this. Hope it's easy enough to understand.

    public String removingLeadingZero(final String number) {
        if (StringUtils.isEmpty(number)) {
            return number;
        }
        int i = 0;
        while (number.charAt(i) == '0') { // Here'0' can be replaced with any charater you want
            i++;
        }
        return number.substring(i);
    }

If your strings are regular numbers (not containing any chars or non-numerical values), you could just cast your string to long and back. This will automatically remove all starting zeros.

String frontTrimmed = Long.parseLong(stringValue, 10) + "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM