OneBite.Dev - Coding blog in a bite size

split a string in java

Code snippet on how to split a string in java

String str = "Welcome to the programming world"; 

String[] words = str.split("\\s");  

for(String w:words){  
    System.out.println(w);  
}  

This code starts by declaring a string variable named “str” and assigning it a value of “Welcome to the programming world”. Then, it uses the split method to split the string into individual words. The split method takes in a regular expression pattern as its parameter - in this case, “\s” defines the pattern to split along spaces. Finally, the for loop prints each word of the array to the console one by one.

java