Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Token Grabber
public class TokenGrabber {
private static final char SEPARATOR = '|';
public static String grabTokenAt(String str, int index, char delim) {
if (index > -1) { // Within minimum bounds.
int pos = -1, step = 0;
if (index > 0) {
for (; step <= index; step++) {
pos = str.indexOf(delim, pos + (step > 1 ? 1 : 0));
}
}
if (pos < 0 && step > 0) return null; // Out of maximum bounds.
int end = str.indexOf(delim, pos + 1);
if (end == -1) end = str.length();
return str.substring(pos + 1, end);
}
return null;
}
public static String grabTokenAt(String str, int index) {
return grabTokenAt(str, index, SEPARATOR);
}
public static void main(String[] args) {
String str = "foo|bar|baz|fizz|buzz";
int frequency = new java.util.StringTokenizer(str, "|").countTokens();
for (int i = -1; i <= frequency; i++) {
System.out.printf("Token: %2d => %s%n", i, grabTokenAt(str, i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment