Tuesday, February 27, 2007

String Parsing in Java

In Awk you can easily find the position of a delimiter and then take all characters up to that point by using the index() and substr() functions. But how does that work in Java? Is there an easy way to parse a String and carry out these type of routine actions?

Here you go:

subtring method:

int start = 1;
int end = 4;
String substr = "aString".substring(start, end); // Str
index method:
String string = "madam, i am Adam";
// First occurrence of a c
int index = string.indexOf('a'); // 1
Here is a live example I am working with where I need to parse the String into two variables as my webpage is passing me a parameter that is pipe-delimited:

String str = "YES|12345";

int pipe = str.indexOf('|'); //4

String firstPart = str.substring(1,pipe-1);
String lastPart = str.substring(pipe+1);