Search code examples
javastringinputnumber-formattingphone-number

Remove spaces from a integer - Java


How would I go about changing an integer like '905 123 7023' into something like '9051237023'.

The assignment is supposed to determine if the phone number inputed is a real phone number.

I was going to use this:

int phoneNumber;
// Code that turns number with spaces into single number
try {
  System.out.println("Please input an integer");
  input = TextIO.getlnInt();
}

catch (InputMismatchException exception) {
  System.out.println("This is not an phone number");
}

To determine the code


Solution

  • The data the user is going to enter will be a string (as it could include spaces, and possibly even letters).

    There are several ways to remove spaces from a string:

    1. Use split() and join() to split on spaces and join without them
    2. use indexOf() to find spaces, remove them using substring, and iterate until no more spaces
    3. iterate every character of the string, building a new string out of non-space characters
    4. use a regular expression
    5. use replace() (thanks @David Wallace - I completely overlooked the obvious one)