-1

i need to convert String to array of Strings. eg:

String words = "one, two, three, four, five";

into array like

String words1[];
String words1[0]="one";
       words1[1]="two";
       words1[2]="three";
       words1[3]="four";
       words1[4]="five";  

please guide me

Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
  • 5
    read Java basics. I guess all you need to initialize perhaps. `String[] words1 = new String[5]` that's all. don't use conflicting name like `Words1`, and `words1`. Also variables start with small letter. – Nishant Sep 07 '12 at 05:22
  • Use your mind. that's it – Jayant Varshney Sep 07 '12 at 12:27

4 Answers4

2

I think perhaps what you are looking for is:

String words = "one two three four five";
String[] words1 = words.split(" ");
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
2

The exact answer will be using split() function as everyone suggested:

String words = "one, two, three, four, five";
String words1[] = words.split(", ");
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
0

Try this,

 String word = " one, two, three, four, five";        
 String words[] = word.split(",");
 for (int i = 0; i < words.length; i++) {
     System.out.println(words[i]);
 }

if you need to remove space, you can call .trim(); method through the loop.

mssb
  • 878
  • 1
  • 8
  • 19
0

Here i code something may it helpful to you just take a look.

import java.util.StringTokenizer;

public class StringTokenizing
{
 public static void main(String s[])
 {
   String Input="hi hello how are you";
 int i=0;
   StringTokenizer Token=new StringTokenizer(Input," ");
   String MyArray[]=new String[Token.countTokens()];
   while(Token.hasMoreElements())
   {
    MyArray[i]=Token.nextToken();
    System.out.println(MyArray[i]);
    i++;
   }
  }
 }
SKJ
  • 46
  • 4