How to split string in java Program

public class SplitExample {
  public static void main(String args[]) {
    String s1 = "java string split method by TechSarvam";
    String[] words = s1.split("\\s"); //splits the string based on whitespace
    //using java foreach loop to print elements of string array
    for (String w: words) {
      System.out.println(w);
    }
  }
}

Step-by-Step Breakdown:

1. Class Declaration:

public class SplitExample 

{

   public static void main(String args[]) 

   {

  • This declares a class called SplitExample.
  • The class contains the declaration of the entry point for an application from where execution starts.

2. String Declaration

String s1 = “java string split method by TechSarvam”;

  • Declared and initialized a variable of type string named s1 with the string value “java string split method by TechSarvam”.
  • It is a string containing more than one word with whitespaces for separation.

3. Using split() Method

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

  • The split(\\\\\\\”\\\\\\\\\\\\\\\\s\\\\\”) method splits the string s1 into the array substrings with help of a delimiter: spaces, tabs, new lines, etc. for the s1.
  • The regular expression \\\\\\\\\\\\\\\\\\\\\\\\s is shorthand for a whitespace character.
  • The split() method will return a string array. Each string of the array is one word of the original string s1.
  • After this splitting, words array will consist of the following elements:

[java, string, split, method, by, TechSarvam]

4. Using a for-each Loop to Print Words:

for (String w : words)

   System.out.println(w);

  • This is a for-each loop that steps through the words array.
  • The variable w holds each word in the words array.
  • In the loop, System.out.println(w); prints each word on a new line.

5. Program Output:

The program will print each word from the words array, with each word appearing on a new line:

java

string

split

method

by

TechSarvam

Summary

  • The program uses the split(\”\\\\s\”) function to split the given string s1 into an array of words based on spaces (whitespace).
  • Then with the help of a for-each loop, the program prints every word in the result array.
  • The output of the program will be every word in the input string s1, but this time on separate lines.

Leave a Comment

Your email address will not be published. Required fields are marked *