-1

I need help with splitting a String array at each , and make the result a new string array.

String [] studentName ={"Thui Bhu, 100, 90, 80, 100, 89, 99, 88"}

Convert to:

String []studentName2={"Thui Bhu", "100", "90", "80", "100" "89", "99", "88"}
Pang
  • 9,564
  • 146
  • 81
  • 122
Kelvin Chen
  • 11
  • 1
  • 2

3 Answers3

2

specify the index of the array element where the splitting going to be occur.

    String [] studentName ={"Thui Bhu, 100, 90, 80, 100, 89, 99, 88"};
    System.out.println(Arrays.toString(studentName[0].split(",")));
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You could use a regular expression ,\\s* to split on a comma and consume any (optional) white-space like

String[] studentNames = { "Thui Bhu, 100, 90, 80, 100, 89, 99, 88" };
for (String studentName : studentNames) {
    String[] arr = studentName.split(",\\s*");
    System.out.println(Arrays.toString(arr));
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

StringTokenizer implementation would be something like that:

StringTokenizer str = StringTokenizer(yourString, ",");

while(str.hasMoreTokens())
{
   //whatever you want to do here
}

Note: It is a legacy class and its use is discouraged.

Recommended way: Using split method of string is the recommended way.
Following is the example:

String[] result = "this,is,a,test".split(",");
     for (int x=0; x<result.length; x++)
         System.out.println(result[x]);

Output:
this
is
a
test

Junaid
  • 4,822
  • 2
  • 21
  • 27