How to split a string into a number of substrings in Java



Problem Description

How to split a string into a number of substrings?

Solution

Following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings.

public class JavaStringSplitEmp{
   public static void main(String args[]) {
      String str = "jan-feb-march";
      String[] temp;
      String delimeter = "-";
      temp = str.split(delimeter);
      
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         str = "jan.feb.march";
         delimeter = "\\.";
         temp = str.split(delimeter);
      }
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         temp = str.split(delimeter,2);
         
         for(int j = 0; j < temp.length; j++){
            System.out.println(temp[j]);
         }
      }
   }
}

Result

The above code sample will produce the following result.

jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march

This is another example of string split

public class HelloWorld {
   public static void main(String args[]) {
      String s1 = "t u t o r i a l s"; 
      String[] words = s1.split("\\s"); 
      for(String w:words) {
         System.out.println(w);  
      }  
   }
}

Result

The above code sample will produce the following result.

t 
u 
t 
o 
r 
i 
a 
l 
s 
java_strings.htm
Advertisements