Advertisement
MrPolywhirl

String Token Grabber

Nov 2nd, 2016
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1.  
  2. public class TokenGrabber {
  3.     public static String grabToken(String str, int index, char delim) {
  4.         if (index > -1) { // Within minimum bounds.
  5.             int pos = -1, step = 0;
  6.             if (index > 0) {
  7.                 for (; step <= index; step++) {
  8.                     pos = str.indexOf(delim, pos + (step > 1 ? 1 : 0));
  9.                 }
  10.             }
  11.             if (pos < 0 && step > 0) return null; // Out of maximum bounds.
  12.             int end = str.indexOf(delim, pos + 1);
  13.             if (end == -1) end = str.length();
  14.             return str.substring(pos + 1, end);
  15.         }
  16.         return null;
  17.     }
  18.  
  19.     public static String grabToken(String str, int index) {
  20.         return grabToken(str, index, '|');
  21.     }
  22.    
  23.     public static void main(String[] args) {
  24.         String str = "foo|bar|baz|fizz|buzz";
  25.        
  26.         System.out.println(grabToken(str, -1)); // null
  27.         System.out.println(grabToken(str, 0));  // foo
  28.         System.out.println(grabToken(str, 1));  // bar
  29.         System.out.println(grabToken(str, 2));  // baz
  30.         System.out.println(grabToken(str, 3));  // fizz
  31.         System.out.println(grabToken(str, 4));  // buzz
  32.         System.out.println(grabToken(str, 5));  // null
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement