java 如何在字符数组中搜索特定字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7478210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:09:38  来源:igfitidea点击:

How to search a char array for a specific char?

javaarrays

提问by Samir Talwar

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();

对于 lengthOfArray 如果 array[i].equals(" ") doSomething();

But I cant find array methods to that comparison.

但是我找不到该比较的数组方法。

回答by Brian Colvin

Or the old fashioned way

或者老式的方式

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

回答by Samir Talwar

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

这不完全是您所要求的,但无论如何我都会把它扔掉:如果您有一个String而不是char数组,您可以用空格分割以获得包含单独单词的字符串数组。

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.

\s+正则表达式匹配的一个或多个空白字符(空格,回车,等),因此该字符串将是任何空白分裂。

回答by Michael Berry

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

回答by Leo Izen

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