Scott Scott - 1 year ago 57
Java Question

Java: Checking each space in a String

I'm sure this is fairly simple, however I've tried googling the question but can't find an answer that fits my problem.

I'm playing around with string manipulation and one of the things I'm trying to do is get the first letter of each word. (And then place them all into a string)

I'm having trouble with registering each 'space' so that my If statement will be triggered. Here's what I have so far.

while (scanText.hasNext()) {
boolean isSpace = false;
if (scanText.hasNext(" ")) {isSpace = true;}

String s =;

if (isSpace) {firstLetters += s + " ";}

Also, if there is a much better way to do this then please let me know

Answer Source

You can also split the original text by spaces, and collect the words.

String input = "    Hello world    aaa     ";
String[] split = input.trim().split("\\s+"); // all types of whitespace; " +" to pick spaces only
// operate on "split" array containing words now: [Hello, world, aaa]

However using regexps here might be overkill.