-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

2
  • 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. Commented Sep 7, 2012 at 5:22
  • Use your mind. that's it Commented Sep 7, 2012 at 12:27

4 Answers 4

2

I think perhaps what you are looking for is:

String words = "one two three four five";
String[] words1 = words.split(" ");
2

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

String words = "one, two, three, four, five";
String words1[] = words.split(", ");
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.

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++;
   }
  }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.