Created
December 21, 2016 18:38
-
-
Save rmkane/a6a95750dfe4d42f8805889832727439 to your computer and use it in GitHub Desktop.
Token Grabber
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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