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?