开发者

How to search a char array for a specific char?

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 w开发者_如何学运维ord. 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.


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.


Or the old fashioned way

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


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
    }
}


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜