我需要將字符串轉換爲字符串數組。例如:將字符串轉換爲java中的數組字符串
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";
請指導我
我需要將字符串轉換爲字符串數組。例如:將字符串轉換爲java中的數組字符串
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(", ");
試試這個,
String word = " one, two, three, four, five";
String words[] = word.split(",");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
,如果你需要刪除的空間,你可以調用通過循環.trim();
方法。
在這裏,我編碼的東西可能有助於你只是看看。
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++;
}
}
}
閱讀Java基礎知識。我猜你可能需要初始化。 'String [] words1 = new String [5]'就是這樣。不要使用像'Words1'和'words1'這樣衝突的名字。變量也以小寫字母開頭。 – Nishant
用你的心思。而已 –