Skip to content

Instantly share code, notes, and snippets.

@rmkane
Created December 21, 2016 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmkane/a6a95750dfe4d42f8805889832727439 to your computer and use it in GitHub Desktop.
Save rmkane/a6a95750dfe4d42f8805889832727439 to your computer and use it in GitHub Desktop.
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