Say we would like to write a method to receive entire book in a string and an arbitrary single-character delimiter to separate strings and return an array of strings. I came up with the following implementation (Java).(suppose no consecutive delimiter etc)
ArrayList<String> separater(String book, char delimiter){
ArrayList<String> ret = new ArrayList<>();
String word ="";
for (int i=0; i<book.length(), ++i){
if (book.charAt(i)!= delimiter){
word += book.charAt(i);
} else {
ret.add(word);
word = "";
}
}
return ret;
}
Question: I wonder if there is any way to leverage String.split() for shorter solutions? Its because I could not find a general way of defining a general regex for an arbitrary character delimiter.
String.split("\\.") if the delimiter is '.'
String.split("\\s+"); if the delimiter is ' ' // space character
That measn I cold not find a general way of generating the input regex of method split() from the input character delimiter. Any suggestions?
String[] array = string.split(Pattern.quote(String.valueOf(delimiter)));
That said, The Guava Splitter is much more versatile and well-behaving than String.split()
.
And a note on your method: concatenating to a String in a loop is very inefficient. As Strings are immutable, it produces a lot of temporary Strings and StringBuilders. You should use a StringBuilder instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.