Этот фрагмент кода разбивает строку на подстроки на основе заданного разделителя. Например, строка:
String str = "foo,bar,foobar";
String[] strArray = split(str, ',' true);
будет возвращено как этот массив строк:
strArray ==> [ "foo", "bar", "foobar" ];
public String[] split(String toSplit, char delim, boolean ignoreEmpty) {
StringBuffer buffer = new StringBuffer();
Stack stringStack = new Stack();
// Loop through each char in the string (so 'f', then 'o', then 'o' etc).
for (int i = 0; i < toSplit.length(); i++) {
if (toSplit.charAt(i) != delim) {
// If the char at the current position in the string does not equal
// the delimiter, add this char to the string buffer (so we're
// building up another string that consists of letters between two
// of the 'delim' characters).
buffer.append((char) toSplit.charAt(i));
} else {
// If the string is just whitespace or has length 0 and we are
// removing empty strings, do not include this substring
if (buffer.toString().trim().length() == 0 && ignoreEmpty) {
} else {
// It's not empty, add this substring to a stack of substrings.
stringStack.addElement(buffer.toString());
}
// Reset the buffer for the next substring.
buffer = new StringBuffer();
}
}
if (buffer.length() !=0) {
// Make sure to add the last buffer/substring to the stack!
stringStack.addElement(buffer.toString());
}
// Make an array of string the size of the stack (the number of substrings found)
String[] split = new String[stringStack.size()];
for (int i = 0; i < split.length; i++) {
// Pop off each substring we found and add it into the array we are returning.
// Fill up the array backwards, as we are taking values off a stack.
split[split.length - 1 - i] = (String) stringStack.pop();
}
// Unnecessary, but clears the variables
stringStack = null;
buffer = null;
// System.out.println("There are " + split.length + " Words");
return split;
}