noor
noor

Reputation: 3004

Ignore the last delimeter in java string tokenizer

I have a string like this "AddUser_test_NewUserForm_singinprocess".

By using the java string tokenizer, i want the output like this:

Adduser

test

NewUserForm_singinprocess

The delemeter is " _ " and my main target is to ignore the last " _ " in " NewUserForm_singinprocess " as a delimeter.

how i can do this ?

Upvotes: 1

Views: 119

Answers (2)

Rahman
Rahman

Reputation: 3785

String strWithDelimeter = "Hello_Hi_Good_Morning";

    StringTokenizer strToken = new StringTokenizer(strWithDelimeter, "_");
    int noOfToken = strToken.countTokens();
    int count =1;
    String currentElement = null, lastElement = null,lastElement2 = null;
    while(strToken.hasMoreTokens()) {
        currentElement = strToken.nextToken().toString();
        if(count == noOfToken)
            lastElement = currentElement;
        else if(count == noOfToken-1)
            lastElement2 = currentElement;
        else 
            System.out.println(currentElement);
        count++;
    }
    System.out.println(lastElement2+"_"+lastElement);

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

You can use String#split() to achieve this easily :

public static void main(String args[]) throws Exception {
    String s = "AddUser_test_NewUserForm_singinprocess";
    System.out.println(Arrays.toString(s.split("_(?=.*_)")));
}

O/P :

[AddUser, test, NewUserForm_singinprocess]

Upvotes: 1

Related Questions