How to split a String via Java

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 wordsThisisatestString

 

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set