我需要将字符串转换为字符串数组。例如:
String words = "one, two, three, four, five";
像数组一样
String words1[];
String words1[0]="one";
words1[1]="two";
words1[2]="three";
words1[3]="four";
words1[4]="five";
请指导我
我想也许你正在寻找的是:
String words = "one two three four five";
String[] words1 = words.split(" ");
确切的答案将是使用split()
每个人都建议的函数:
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.
在这里,我编写了一些代码,可能对您有帮助,请看一下。
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++;
}
}
}