Thursday 11 May 2017

How to split a string contians special characters in java

Java Split String Example showing special characters or regular expressions (regex):



Sometimes we need to split String in java, which contains the special characters such as '(',  '*' ,  '&', '<' ,  '^' etc., .

Now we will see how to split them in java.

The following example shows how to split a special characters '(', '*'.


Example: Splitspecialcharacter.java




package com.practice.corejava;

public class Splitspecialcharacter {

              public static void main(String[] args) {

                             String str = "CLOTHS(10*12*13*7)";
                                           String[] mystr = str.split("\\(");
                                          
                                           System.out.println("Splitted string After the special character '(':");
                                           for(String str2 : mystr){
                                                         
                                                          //Displaying the string after splitting it after the special character '('
                                                          System.out.println(str2);
                                                         
                                                          if(str2.contains("*")){
                                                                       
                                                                        String[] tempString = str2.split("\\*");
                                                                        System.out.println("Splitted string after the special character
                                                  '*':");
                                                                        for(String temp: tempString){
                                                                                      //Displaying the string after splitting it after the special
                                                                        character '*'
                                                                                      System.out.println(" "+temp);
                                                                                       }
                                                                        }                                         
                                                          }
                                     }
                                   }

Now we will run the above example in eclipse and see the output as follows:

Console:

Split After the special character '(':
 CLOTHS
 10*12*13*7)

Spliting after the special character '*':
 10
 12
 13
 7)



No comments:

Post a Comment