简体   繁体   中英

How to declare string array of unknown size as input then tokenize

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 )

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());
        }
    }
}

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]

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