Pregunta

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]);
            }
        }
    }
¿Fue útil?

Solución

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().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top