Skip to content

Commit

Permalink
Added utility to split on whitespaces.
Browse files Browse the repository at this point in the history
  • Loading branch information
fabioz committed Aug 13, 2013
1 parent 1f90445 commit 25f075e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,17 @@ public void testIterLines() throws Exception {
arrayList.clear();
}

public void testSplitOnWhitespaces() throws Exception {
String[] split = StringUtils.splitInWhiteSpaces("aaa bb ").toArray(new String[0]);
assertTrue(Arrays.equals(new String[] { "aaa", "bb" }, split));

split = StringUtils.splitInWhiteSpaces("aaa bb").toArray(new String[0]);
assertTrue(Arrays.equals(new String[] { "aaa", "bb" }, split));

split = StringUtils.splitInWhiteSpaces(" ").toArray(new String[0]);
assertTrue(Arrays.equals(new String[] {}, split));
}

public void testSplit() throws Exception {
String[] split = StringUtils.split("aaa bb ", ' ').toArray(new String[0]);
assertTrue(Arrays.equals(new String[] { "aaa", "bb" }, split));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,47 @@ public static List<String> split(String string, char toSplit) {
return ret;
}

/**
* Splits the given string in a list where each element is a line.
*
* @param string string to be split.
* @return list of strings where each string is a line.
*
* @note the new line characters are also added to the returned string.
*/
public static List<String> splitInWhiteSpaces(String string) {
ArrayList<String> ret = new ArrayList<String>();
int len = string.length();

int last = 0;

char c = 0;

for (int i = 0; i < len; i++) {
c = string.charAt(i);
if (Character.isWhitespace(c)) {
if (last != i) {
ret.add(string.substring(last, i));
}
while (Character.isWhitespace(c) && i < len - 1) {
i++;
c = string.charAt(i);
}
last = i;
}
}
if (!Character.isWhitespace(c)) {
if (last == 0 && len > 0) {
ret.add(string); //it is equal to the original (no char to split)

} else if (last < len) {
ret.add(string.substring(last, len));

}
}
return ret;
}

/**
* Splits the given string in a list where each element is a line.
*
Expand Down

0 comments on commit 25f075e

Please sign in to comment.