Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

How to Split a String into a Number of Substrings in Java



String splitting is the act of dividing a string into smaller parts using a specific delimiter. This helps in handling sections of the string separately. The following are the different methods in Java to split a string into a number of substrings

  • Using the string split() method

  • Using the string split() method with whitespace

Split string using split() method

The string split method divides a string into substrings based on a delimiter, returning an array of these substrings for further use.

Example

The 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 

Output

jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march

Split string using split() method with whitespace

We will know how to split a string using whitespace as the delimiter. The split method, with the delimiter separating the string wherever a space appears, gives an array of substrings that are printed one by one.

Example

The following example splits a string into a number of substrings using the split Method with Whitespace

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);  
      }  
   }
}

Output

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