Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TokenGrabber {
- public static String grabToken(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 grabToken(String str, int index) {
- return grabToken(str, index, '|');
- }
- public static void main(String[] args) {
- String str = "foo|bar|baz|fizz|buzz";
- System.out.println(grabToken(str, -1)); // null
- System.out.println(grabToken(str, 0)); // foo
- System.out.println(grabToken(str, 1)); // bar
- System.out.println(grabToken(str, 2)); // baz
- System.out.println(grabToken(str, 3)); // fizz
- System.out.println(grabToken(str, 4)); // buzz
- System.out.println(grabToken(str, 5)); // null
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement