» » How to split a string in java


#1: Java Program to split a String using String Split() method:

  1. package com.instanceofjava;
  2.  
  3. class SplitString{
  4.  
  5. public static void main(String [] args){ 

  6.   String str = "Instance-of-Java";
  7.   String strarray[]=str.split("-");
  8.  
  9.     for (int i = 0; i < strarray.length; i++) {
  10.         System.out.println(strarray[i]);
  11.     }
  12.    
  13. }
  14. }
Output:
  1. Instance
  2. of
  3. Java

#2: Java Program to split a String using String Split() method and use for each loop to display
  1. package com.instanceofjava;
  2.  
  3. class SplitString{
  4.  
  5. public static void main(String [] args){ 

  6.   
  7.     String str = "Instance-of-Java";
  8.     String strarray[]=str.split("-");
  9.  
  10.     for (String string : strarray) {
  11.         System.out.println(string);
  12.     }
  13.  
  14. }
  15. }


Output:
  1. Instance
  2. of
  3. Java



#3: Java Program to split a String using String Split() method: Before splitting check whether deliminator is there or not
  1. package com.instanceofjava;
  2.  
  3. class SplitString{
  4.  
  5. public static void main(String [] args){ 

  6.   
  7.     String str = "Instance-of-Java";
  8.    if(str.contains("-")){
  9.  
  10.     String strarray[]=str.split("-");
  11.  
  12.     for (String string : strarray) {
  13.         System.out.println(string);
  14.     }
  15.  
  16.     }
  17.     else{
  18.         System.out.println("String does not conatain specified char so splitting is not possible");
  19.     }
  20.  
  21. }
  22. }
Output:
  1. Instance
  2. of
  3. Java

#4: Java Program to split a String using String Split() method: Before splitting check whether deliminator is there or not
  1. package com.instanceofjava;
  2.  
  3. class SplitString{
  4.  
  5. public static void main(String [] args){ 

  6.   
  7.     String str = "Instance-of-Java";
  8.    if(str.contains(".")){
  9.  
  10.     String strarray[]=str.split("-");
  11.  
  12.     for (String string : strarray) {
  13.         System.out.println(string);
  14.     }
  15.  
  16.     }
  17.     else{
  18.         System.out.println("String does not contains specified char so splitting is not possible");
  19.     }
  20.  
  21. }
  22. }
Output:
  1. String does not contains specified char so splitting is not possible

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu