如何访问String数组中的每个单词?

时间:2015-04-16 19:26:17

标签: java arrays string split

我的程序使用以下句子读取file

  

钟敲响了一下

我将此句子放入String并在每个空白处拆分String

我唯一的问题是如何访问此array中的每个字词?此外,这些字词是单个字符串还是在Integer中的array位置表示为JFileChooser cho = new JFileChooser(); File file = cho.getSelectedFile(); String string = readFile(file); for(int i = 1; i <= string.length(); i++) { String [] words = string.split(" "); //This is where I'm stuck }

{{1}}

5 个答案:

答案 0 :(得分:4)

JFileChooser cho = new JFileChooser();
File file = cho.getSelectedFile();
String string = readFile(file);
String [] words = string.split(" "); // split the input and assign to an array

for (int i = 0; i < words.length; i++) { // loop through the array that was created
    System.out.println(words[i]); // print each String in the array
}

答案 1 :(得分:2)

拆分字符串,然后使用你的循环遍历数组。

String[] words = string.split(" ");
for(int i = 0; i < words.length; i++){
    //iterate over words array using words[i] as your accessor. 
}

答案 2 :(得分:1)

将String拆分为块并将它们放入数组

String text = "The clock struck one";
String [] chunks = text.split(" ");

它们存储在其中并分配给整数索引,如:

String firstChunk = chunks[0]; 

firstChunk的内容是“The”。 如果您想迭代数组并访问块,您可以这样做:

for (String chunk : chunks) {
    System.out.println(chunk);
}

但这是一个非常基本的问题。你应该研究更多类似的东西。

答案 3 :(得分:0)

String string = "blah1 blah2 blah3";
String[] words = string.split("");

在那里words[0]是blah1,words[1]是blah2而words[2]是blah3。 然而,这不适用于昏迷或点。

答案 4 :(得分:-1)

JFileChooser cho = new JFileChooser();
File file = cho.getSelectedFile();
String string = readFile(file);
String [] words = string.split(" ");

for(String word: words){
    System.out.println(word)
}