如何声明未知大小的字符串数组作为输入然后标记化

时间:2021-12-27 21:26:26

I am trying to declare an array of String which will consist of the input, that is unknown (it depends what text user inputs). I set up a Scanner to read the input then declared a String[] to store the input, and a while loop to go through each line of text and delimit on " ". My question is: How do I set up the array of String to contain the input so I can break it apart into words in the while loop (I can't use ArrayList)

我试图声明一个String数组,它将包含输入,这是未知的(它取决于用户输入的文本)。我设置了一个Scanner来读取输入然后声明一个String []来存储输入,并设置一个while循环来遍历每行文本并分隔“”。我的问题是:如何设置String数组以包含输入,以便我可以将它分成while循环中的单词(我不能使用ArrayList)

public     class Scramble {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] words;

        String line;
        while (in.hasNext()) {
            words.add(line.trim());
        }
    }
}

1 个解决方案

#1


2  

read the whole sentence and do it like this

阅读整个句子并按照这样做

    Scanner in = new Scanner(System.in);
    String sentence = in.nextLine ();
    String[] words = sentence.split(" ");

    System.out.println(Arrays.toString(words));

Input

this is a test

这是一个测试

Output

[this, is, a, test]

[这是一个测试]

#1


2  

read the whole sentence and do it like this

阅读整个句子并按照这样做

    Scanner in = new Scanner(System.in);
    String sentence = in.nextLine ();
    String[] words = sentence.split(" ");

    System.out.println(Arrays.toString(words));

Input

this is a test

这是一个测试

Output

[this, is, a, test]

[这是一个测试]