Home | Need Help? | Archives
January 20, 2011 2:29 am
Today 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:
Mobile Site | Full Site
Get a free blog at WordPress.com Theme: WordPress Mobile Edition by Alex King.
Simple but very useful
LikeLike
By Sankar R K on September 29, 2011 at 12:26 pm
what about NOT using SPLIT? haven’t learned it yet.
LikeLike
By Scot Zarnoth on October 23, 2011 at 9:22 pm