-1

When we enter a no like "00982787878" (having 9 digits and zeros) the output should not be displayed after the zeros are trimmed.

Problem:

There is some problem in while loop as the output is a number with just one 0 trimmed.

Code:

public static String trimZeros(String mobNumber)
{
        boolean exitLoop = true;
        int count = 0;


        while (exitLoop && mobNumber.substring(count) == "0") 
            mobNumber = mobNumber.substring(0);
        
        if (mobNumber.charAt(count) != '0')
        {
            exitLoop = false;
        }
        count++;
        mobNumber = mobNumber.replaceAll(" ", "");
        mobNumber = mobNumber.length() < 10 ? mobNumber.substring(mobNumber
                .length()) : mobNumber.substring(mobNumber.length() - 10);
        
        return mobNumber;
}
Community
  • 1
  • 1
kushal_n
  • 19
  • 1
  • 3
    So, do you have a question? – Zéychin Oct 28 '14 at 16:02
  • Why are you removing digits from a phone number? That doesn't make sense - you're changing the number. – JonK Oct 28 '14 at 16:02
  • 2
    Don't compare Strings with == – Eran Oct 28 '14 at 16:04
  • Whats the problem you are facing here – Chiseled Oct 28 '14 at 16:04
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Tom Oct 28 '14 at 16:16
  • i just want to remove zeros at the beginning, if the no. remaining after removing zeroes is less than 10 digits then it should not display anything...just blank. and if the no. is greater than 10 digits, it should display the last 10 digits BUT WITHOUT ZEROES IN THE BEGINNNG – kushal_n Oct 28 '14 at 16:25
  • 2
    http://stackoverflow.com/questions/15889853/how-to-remove-leading-zeros-from-numeric-text – Infinite Recursion Oct 28 '14 at 16:26

1 Answers1

0

If I correctly understood your problem:

public static String trimZeros(String number) {

    //trim zeros at left
    number = number.replaceAll("^0*", "");

    //if the length is < 10, returns an empty string
    if (number.length() < 10) {
        return "";
    }

    //if the length is > 10, trims any number at left
    if (number.length() > 10) {
        number = number.replaceAll(".*(\\d{10})$", "$1");
    }

    return number;
}
elias
  • 15,010
  • 4
  • 40
  • 65
  • NO, it should not throw any exception, it should just not display anything. also, what if the no. is greater than 10 – kushal_n Oct 28 '14 at 16:29
  • @hotshot02 So just replace the `throw` with `return "";` then? Also, `!= 10` covers numbers that are both shorter and longer than 10 digits. I still don't understand what purpose mangling the phone number serves thought. – JonK Oct 28 '14 at 16:56