[Q#7478210][A#7478238] How to search a char array for a specific char?
https://stackoverflow.com/q/7478210
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.
Answer
https://stackoverflow.com/a/7478238
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. The \s+ regular expression matches one or more whitespace characters (space, carriage return, etc.), so the string will be split on any whitespace.
APIzation
String s = new String(array);
String[] words = s.split("\\s+");
// words = { "robots", "laser", "car" }
package com.stackoverflow.api;
public class Human7478238 {
public static String[] splitStringBySpaces(String array) {
String s = new String(array);
String[] words = s.split("\\s+");
return words;
}
}
package com.stackoverflow.api;
/**
* How to search a char array for a specific char?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/7478238">https://stackoverflow.com/a/7478238</a>
*/
public class APIzator7478238 {
public static void searchArray(String array) throws Exception {
String s = new String(array);
String[] words = s.split("\\s+");
// words = { "robots", "laser", "car" }
}
}