java-string-examplesStrings

How to split a String via Java

Posted On
Posted By admin

In this blog post, I will be explaining how you can split a String via Java. Consider the following code snippet:


package learnjava.strings;

public class SplitStringDemo {

public static void main(String[] args) {
String str = "This is a test String";
String[] words = str.split(" ");
System.out.println("There are "+words.length+" words");
for(String word:words){
System.out.println(word);
}

}

}

There is a method called String.split. It accepts any regular expression. It splits the String around matches of the specified regular expression. Here, I am simply using a space. This will split the input sentence into words. So if you run the above code, you will get the following output:

There are 5 words
This
is
a
test
String

 

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment