i have a problem with split(). When entering a text like "This is a text" it only prints "This".

public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Enter bta3 ");
        Scanner s1 = new Scanner(System.in);
        String toParse = s1.next();
        String delims = "[ ]+";
        String[] tokens = toParse.split(delims);
        for (int i = 0; i < tokens.length; i++) {
            {
                System.out.println(tokens[i]);
            }
        }
    }
有帮助吗?

解决方案

Your problem is not with split but with Scanner, which by default uses one or more continues whitespaces as delimiter, so s1.next() will return only one word from user input (with no whitespaces) which means

String toParse = s1.next();

for input like This is a text will become This (so there are no whitespaces to split on)

If you want to read entire data from user input use s1.nextLine().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top