-2

Possible Duplicate:
Java: How to convert comma separated String to ArrayList

I have a the String Red*Blue*Yellow*Green*White. How do I break that String out by * into a List<String>?

Community
  • 1
  • 1
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
  • 3
    There must be hundreds of questions on this topic here on SO, please search before posting. – Keppil Oct 26 '12 at 22:43

3 Answers3

2

You can try this: -

String str = "Red*Blue*Yellow*Green";
String[] arr = str.split("\\*");
List<String> list = new ArrayList<String>(Arrays.asList(arr));

NOTE:-

Arrays.asList returns you an unmodifiable list, so if you want a modifiable list, you need to create a new list by using the constructor of ArrayList, that takes a Collection object as parameter.

Also, since * is a special character in Regex, and String.split() takes a Regex for splitting. So, you need to escape the * with a backslash.

OUTPUT: -

[Red, Blue, Yellow, Green]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1
  String[] str ="Red*Blue*Yellow*Green*White".split("\\*");
    List<String> list = Arrays.asList(str);

Output:

[Red, Blue, Yellow, Green, White]
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
1

Please try this

       String ss="Red*Blue*Yellow*Green*Whit";
       String sss[] = ss.split("\\*");
       List <String> ssss = Arrays.asList(sss);
sunleo
  • 10,589
  • 35
  • 116
  • 196