saplingPro
saplingPro

Reputation: 21329

How can I remove the empty string resulting from a split?

When I split a String :

A.B.C. 

by .. I get 4 strings. The fourth being the white space. How can I remove that ?

String tokens[] = text.split("\\.");
    for(String token : tokens) {
        System.out.println("Token : " + token);
    }

Upvotes: 0

Views: 703

Answers (3)

Paul Hicks
Paul Hicks

Reputation: 14029

If whitespace at the beginning or end is the problem, trim it off:

String tokens[] = text.trim().split("\\.");

Upvotes: 7

Cast_A_Way
Cast_A_Way

Reputation: 472

Your String is A.B.C. so that whenever you split that it with . it will be give four substrings only. Even though you use trim() it will give four substrings. So try to remove last . and then split string. You will get proper output.

Upvotes: -1

domdomcodecode
domdomcodecode

Reputation: 2453

Remove all the whitespace with a replaceAll() before your code.

text.replaceAll("\\s+","");

Upvotes: 1

Related Questions