Skip to content

Instantly share code, notes, and snippets.

@komiya-atsushi
Forked from tamtam180/StringUtils.java
Created June 13, 2012 16:13
Show Gist options
  • Save komiya-atsushi/2925028 to your computer and use it in GitHub Desktop.
Save komiya-atsushi/2925028 to your computer and use it in GitHub Desktop.
なんか構造が美しくないのでリファクタしたい・・ こう書き換えるかな?(komiya)
public static List<String> tokenize(String str) {
if (str == null || str.isEmpty()) {
return Collections.emptyList();
}
ArrayList<String> tokens = new ArrayList<String>();
int i = 0;
char[] chars = str.toCharArray();
while (i < chars.length) {
// TODO while ループの外に出したい。
StringBuilder buffer = new StringBuilder();
while (chars[i] == ' ') {
i++;
}
if (chars[i] == '"') { // フレーズの場合は空白ではない文字まで繰り返す
i++; // SkipDQ
while (i < chars.length && chars[i] != '"') {
buffer.append(chars[i++]);
}
i++; // SkipDQ
} else {
while (i < chars.length && (chars[i] != ' ')) {
buffer.append(chars[i++]);
}
}
String token = buffer.toString().trim();
if (!token.isEmpty()) {
tokens.add(token);
}
}
return tokens;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment