3

Lets say I have a char array that contains the sequences of chars: "robots laser car" I want to search for spaces in this char array in order to identify each separate word. I wanted to do something like this pseudocode below:

for lengthOfArray if array[i].equals(" ") doSomething();

But I cant find array methods to that comparison.

4 Answers 4

6

It's not exactly what you're asking for, but I'll throw it out there anyway: if you have a String instead of a char array, you can split by whitespace to get an array of strings containing the separate words.

String s = new String(array);
String[] words = s.split("\\s+");
// words = { "robots", "laser", "car" }

The \s+ regular expression matches one or more whitespace characters (space, carriage return, etc.), so the string will be split on any whitespace.

Sign up to request clarification or add additional context in comments.

1 Comment

Not what I was looking for, but it seems way more clean and efficient. Thanks.
6

Or the old fashioned way

for(int i = 0; i<array.length; i++){
    if(' ' == array[i]){
        doSomething();
    }
}

Comments

3

Do you just want something like the following that loops through and does something when it gets to a space?

for(char c : "robots laser car".toCharArray()) {
    if(c==' ') {
        //Do something
    }
}

Comments

1

To iterate over the words inside a string, do this:

for (String word : new String(charArray).split("\\s+")){
    doSomething(word); // Such as System.out.println(word);
}

Comments