How can we split or break down a whole sentence into words. ? Yes sometimes it required to do such split in our coding. It is very easy and this is for beginners who trying to learn java programming.
For Example, I need my Java program to split a sentence into string like below:
“This is a sample sentence.”
and turn it into a string array like:
“this”,”is”,”a”,”sample”,”sentence”
Sample Java Code
String s1="This is a sample sentence";
String[] word=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:word){
System.out.println(w);
Result will print as as below:
This
is
a
sample
sentence