How to Ignore White Spaces in Java [Duplicate]

I was wondering how to ignore spaces in Java. This program allows you to enter your first, middle and surname which then outputs your initials. I'm now trying to make it ignore any white spaces. Thanks in advance!

    String fullName;
    char firstName;
    char secondName;
    char surname;
    int space1;
    int space2;

    System.out.println("Please enter your first name, your second name and your surname: ");
    fullName = kybd.nextLine();

    firstName = fullName.charAt(0);
    space1 = fullName.indexOf(" ");
    secondName = fullName.charAt(space1 + 1);
    space2 = fullName.lastIndexOf(" ");
    surname = fullName.charAt(space2 + 1);

    System.out.println("Initials: " + firstName + secondName + surname);
}

}

3

2 Answers

Explanation

You can implicitly ignore them by just removing them from your input text.

Therefore replace all occurrences with "" (empty text):

fullName = fullName.replaceAll(" ", "");

After that call fullName won't contain a whitespace anymore.

However you'll then get a problem with your logic as you split on whitespaces.


Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.