java 如何使用 Scanner 分割以空格为分隔符的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29026079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:33:55  来源:igfitidea点击:

How to split a string with space being the delimiter using Scanner

javajava.util.scanner

提问by Zack

I am trying to split the input sentence based on space between the words. It is not working as expected.

我正在尝试根据单词之间的空格拆分输入句子。它没有按预期工作。

public static void main(String[] args) {
    Scanner scaninput=new Scanner(System.in);
    String inputSentence = scaninput.next();
    String[] result=inputSentence.split("-");
    // for(String iter:result) {
    //     System.out.println("iter:"+iter);
    // }
    System.out.println("result.length: "+result.length);
    for (int count=0;count<result.length;count++) {
        System.out.println("==");
        System.out.println(result[count]);
    }
}

It gives the output below when I use "-" in split:

当我在 split 中使用“-”时,它给出了以下输出:

fsfdsfsd-second-third
result.length: 3
==
fsfdsfsd
==
second
==
third

When I replace "-" with space " ", it gives the below output.

当我用空格“”替换“-”时,它会给出以下输出。

first second third
result.length: 1
==
first

Any suggestions as to what is the problem here? I have already referred to the stackoverflow post How to split a String by space, but it does not work.

关于这里有什么问题的任何建议?我已经参考了 stackoverflow 帖子How to split a String by space,但它不起作用。

Using split("\\s+")gives this output:

使用split("\\s+")给出了这个输出:

first second third
result.length: 1
==
first

回答by Bohemian

Change

改变

scanner.next()

To

scanner.nextLine()

From the javadoc

来自javadoc

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Scanner 使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。

Calling next()returns the next word.
Calling nextLine()returns the next line.

调用next()返回下一个单词
调用nextLine()返回下一

回答by Hoopje

The next()method of Scanneralready splits the string on spaces, that is, it returns the next token, the string until the next string. So, if you add an appropriate println, you will see that inputSentenceis equal to the first word, not the entire string.

next()方法Scanner已经在空格上拆分字符串,即返回下一个标记,字符串直到下一个字符串。因此,如果添加适当的println,您将看到它inputSentence等于第一个单词,而不是整个字符串。

Replace scanInput.next()with scanInput.nextLine().

替换scanInput.next()scanInput.nextLine()

回答by ruakh

The problem is that scaninput.next()will only read until the first whitespace character, so it's only pulling in the word first. So the splitafterward accomplishes nothing.

问题是它scaninput.next()只会读取到第一个空格字符,所以它只会拉入单词first. 所以split后来什么都做不了。

Instead of using Scanner, I suggest using java.io.BufferedReader, which will let you read an entire line at once.

Scanner我建议使用而不是使用java.io.BufferedReader,它可以让您一次阅读整行

回答by Yash Varshney

One more alternative is to go with buffered Reader class that works well.

另一种选择是使用运行良好的缓冲 Reader 类。

String inputSentence;

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            inputSentence=br.readLine();

            String[] result=inputSentence.split("\s+");
rintln("result.length: "+result.length);

            for(int count=0;count<result.length;count++)
            {
                System.out.println("==");
                System.out.println(result[count]);
            }

        }

回答by Android Team

Use src.split("\\s+");instead of inputSentence.split("-");

使用src.split("\\s+");代替inputSentence.split("-");

It splits on every \\swhich represents every non-whitespace character. Result is arrayif elements that were before, between and after that delimiter.

它在\\s代表每个非空白字符的each 上拆分。如果元素在该分隔符之前、之间和之后,则结果为数组

Below is the complete example which you needs.

以下是您需要的完整示例。

Example :

例子 :

public class StringSplit {
    public static void main(String[] args) 
    {
        String src = "first second third";
        String[] stringArray = src.split("\s+");

        System.out.println(stringArray[0]);
        System.out.println(stringArray[1]);
        System.out.println(stringArray[2]);
    }
}

For More details how split("\s+") works refer blow stackoverflow post.

有关 split("\s+") 工作原理的更多详细信息,请参阅 blow stackoverflow 帖子。

How exactly does String.split() method in Java work when regex is provided?

当提供正则表达式时,Java 中的 String.split() 方法究竟是如何工作的?