All About Basic


Home | Need Help? | Archives


Java break string in into individual words: How to split a string according to space,comma, colon and more between them and then save it in an array of string.

January 20, 2011 2:29 am

split string into words and string manipulationToday I am sharing you another basic but important technique about string manipulation. While coding in java, sometimes we need to split or break a string into individual word according to space, commas, colon or any other character between them and then save that individual words into an array of string.

The coding is simple and you can test it according to your need. Just copy the code below and run it in your own machine. Please give comments if this solution is helpful for you.

Code Example:

class SplitDemo {

// Demonstrate split().

public static void main(String args[]) {

String result[];

// Split at spaces.

 String testStr = “This is a test.”;

System.out.println(“\n*********************************”);

System.out.println(“\nOriginal string: ” + testStr);

result = testStr.split(“\\s+”);

System.out.print(“\nSplit at spaces: ” +result[0]+ ” and size of array :”+result.length);

showSplit(result);

// Split on word boundaries.

testStr = “One, Two, and Three.”;

System.out.println(“\nOriginal string: ” + testStr);

result = testStr.split(“\\W+”);

System.out.print(“\nSplit at word boundaries: ” +result[0]);

 showSplit(result);

// Split same string on commas and zero or more spaces.

System.out.println(“\nOriginal string: ” + testStr);

result = testStr.split(“,\\s*”);

System.out.print(“\nSplit at commas: “);

showSplit(result);

// Split on word boundaries, but allow embedded

// periods and @.

testStr = “Jerry Jerry@HerbSchildt.com”;

System.out.println(“\nOriginal string: ” + testStr);

result = testStr.split(“[\\W && [^.@]]+”);

System.out.print(“\nAllow . and @ to be part of a word: “);

 showSplit(result);

// Split on various punctuation and zero or more trailing spaces.

testStr = “This, is. a!:; test?”;

System.out.println(“\nOriginal string: ” + testStr);

result = testStr.split(“[.,!?:;]+\\s*”);

System.out.print(“\nSplit on various punctuation: “);

 showSplit(result);

 System.out.println(“\n*********************************”);

}

 static void showSplit(String[] strs) {

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

System.out.print(strs[i] + “|”);

System.out.println(“\n”);

}

Posted by allaboutbasic

Categories: Java Basic Problems

Tags:

2 Responses to “Java break string in into individual words: How to split a string according to space,comma, colon and more between them and then save it in an array of string.”

  1. Simple but very useful

    Like

    By Sankar R K on September 29, 2011 at 12:26 pm

  2. what about NOT using SPLIT? haven’t learned it yet.

    Like

    By Scot Zarnoth on October 23, 2011 at 9:22 pm

Leave a Reply



Mobile Site | Full Site


Get a free blog at WordPress.com Theme: WordPress Mobile Edition by Alex King.