Link to home
Start Free TrialLog in
Avatar of mr_usmannaeem
mr_usmannaeem

asked on

Spliting a string word into segments

I am trying to spilt a word into segments whenever the char "," occurs in the word.
For example,
String name= "[John, David]"
So the two segments should be John and David, which ignore the following
" [ "
" ] "
 " , "
This can work if I use substring, but I have to have a fixed amount of words, but the number of words will be dynamic.
I can do this with seperate chars and store each segment into an array, but I need help doing it with words.


 
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

String[] nameParts = name.split("[\\[\\,]]");
Typo sorry


String[] nameParts = name.split("[\\[\\],]");
You can also use StringTokenizer class to parse your string into tokens by a specified delimiter, in your case it is comma.

Regards,
Avatar of mr_usmannaeem
mr_usmannaeem

ASKER

public class split{
   public static void main(String[] args) throws Exception{
   String combo="[ABC, B]";
   System.out.println(combo);      
   String[] nameParts = combo.split("[\\[\\],]");
   System.out.println(nameParts[0]);
  }
  }
This is not working
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)