Split string in Java


In java to split string, we use split function of String class.
Example : We want to split string java:advanced:cpp based on : character. We will use it like this-

              String value=  "java:advanced:cpp"
              String[] resultArray = value.split(":")
         
Resultant array will have following values: "java","advanced","cpp"

Split function takes input as regex expression. So if we want to split string based on some special character, then it will not be similar like we did before.
Example:
                   String value = "Java [ advanced [ cpp ";
                   String[] resultArray = value.split("[");

  this will throw a runtime exception PatternSyntaxException. We are trying to split the string based on "[" character, which is open square bracket for a regex expression. So it consider this as open bracket and it looks for closing bracket, So it throws the exception. We can solve this problem by using "\\" before the bracket and it will take this as character.


                   String value = "Java [ advanced [ cpp ";
                   String[] resultArray = value.split("\\[");

This will solve the problem.


                   
         

Comments

Popular posts from this blog

Disable or enable proxy for Internet explorer or Chrome

chm viewer unable to show contents

3 prisoners and 5 hats puzzle