65.9K
CodeProject is changing. Read more.
Home

Simple string parsing in Java

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Mar 19, 2012

CPOL
viewsIcon

71305

How to parse a string in Java.

Introduction

When I started to use the Java Native Interface (JNI) on my projects, I had the need to return a lot of information from a function, keeping the code simple and updatable.

Background

It came to my mind to use a simple way to organize information the same way as the MUMPS programming language uses: in pieces, separated by a specific character (separator).

info1|info2||info4...|infon

If some piece doesn't exist (like in the previous example, info3 doesn't exist), the function will return a null string.

Using the code 

To get the piece of information, you just need to give as argument the string that contains all the information, the separator, and the index of the piece.

public class MainClass {

    public static void main(String[] args) {
        
        String str = "info1|info2||info4|info5";
        
        System.out.println("1:" + str_piece(str, '|', 1));
        System.out.println("2:" + str_piece(str, '|', 2));
        System.out.println("3:" + str_piece(str, '|', 3));
        System.out.println("4:" + str_piece(str, '|', 4));
        System.out.println("5:" + str_piece(str, '|', 5));
        System.out.println("6:" + str_piece(str, '|', 6));
    
    }
    
    private static String str_piece(String str, char separator, int index) {
        String str_result = "";
        int count = 0;
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == separator) {
                count++;
                if(count == index) {
                    break;
                }
            }
            else {
                if(count == index-1) {
                    str_result += str.charAt(i);
                }
            }
        }
        return str_result;
    }
}

The output is:

1:info1
2:info2
3:
4:info4
5:info5
6: 

Conclusion

I hope this tip can help you. Any comments are welcome.