web analytics
How to split a string in Java? Options
renaudj
Posted: Saturday, January 30, 2016 12:54:15 PM

Rank:Member
Groups: Member
Joined: 12/21/2015
Posts: 16
Points: 78

Split method in String class will break a string into tokens or array. By specify regular expression as delimiters, as the example below.Split a string into array, using a space as delimiter.

String str = "This is a test string";

String[] words = str.split(" ");

for (int i=0; i < words.length; i++)

    System.out.println(words[i]);

Output:

This

is

a

test

string

In some case that delimiter has a special meaning in a regular expression. You must add two backslashes (\\..) in front of the delimiter to make it as a character rather than the wildcard in a regular expression. Some examples of delimiter that has a special meaning are a dot(.), a star(*) , ‘|’ etc.

For a dot, must use delimiter as “\\.”

String str = "123.456.789.10.11";

String[] words = str2.split ("\\.");

for (int i=0; i < words.length; i++)

     System.out.println(words[i]);

The special character needs to be escaped with a “\” but since “\” is also a special character in Java, you need to escape it again with another.

Sponsor
Posted: Saturday, January 30, 2016 12:54:15 PM
 
Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.