简体   繁体   中英

convert a string into string of array in java

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

I think perhaps what you are looking for is:

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM