简体   繁体   English

拆分方法拆分为单个字符串

[英]Split method is splitting into single String

I have a little problem: I have a program that split a String by whitespace (only single ws), but when I assign that value to the String array, it has only one object inside. 我有一个小问题:我有一个程序,用空格(仅单个ws)将String拆分,但是当我将该值分配给String数组时,它里面只有一个对象。 (I can print only '0' index). (我只能打印“ 0”索引)。 Here is the code: 这是代码:

public void mainLoop() {
        Scanner sc = new Scanner(System.in);

        String parse = "#start";

        while (!parse.equals("#stop") || !parse.isEmpty()) {
            parse = sc.next();

            String[] line = parse.split("[ ]");
            System.out.println(line[0]);
        }
}

The 'mainLoop' is called from instance by method 'main'. “ mainLoop”是通过实例“ main”从实例中调用的。

By default Scanner#next delimits input using a whitespace. 默认情况下, Scanner#next使用空格分隔输入。 You can use nextLine to read from the Scanner without using this delimiter pattern 您可以使用nextLine从扫描仪读取而不使用此分隔符模式

parse = sc.nextLine();

The previous points mentioned in the comments are still valid 评论中提到的先前观点仍然有效

while (!parse.equals("#stop") && !parse.isEmpty()) {
    parse = sc.nextLine();

    String[] line = parse.split("\\s");
    System.out.println(Arrays.toString(line));
}

When you call next on scanner it returns next token from input. 当您在扫描仪上调用next ,它将从输入中返回下一个令牌。 For instance if user will write text 例如,如果用户将编写文本

foo bar

first call of next will return "foo" and next call of next will return "bar" . 的第一次调用next会返回"foo"和下一个呼叫next会返回"bar"

Maybe consider using nextLine instead of next if you want to get string in form "foo bar" (entire line). 如果要以"foo bar" (整行)的形式获取字符串,则可以考虑使用nextLine而不是next


Also you don't have to place space in [] so instead of split("[ ]") you can use split(" ") or use character class \\s which represents whitespaces split("\\\\s") . 另外,您不必在[]放置空格,因此可以使用split(" ")或使用字符类\\s来表示空格split("\\\\s") ,而不是split("[ ]") split("\\\\s")


Another problem you seem to have is 您似乎遇到的另一个问题是

while( !condition1 || !condition2 )

If you wanted to say that loop should continue until either of conditions is fulfilled then you should write them in form 如果您想说循环应该一直持续到满足两个条件中的任何一个,那么您应该将它们写成表格

while( !(condition1 || condition2) )

or using De Morgan's laws 或使用戴摩根定律

while( !condition1 && !condition2 )

如果要按单个空格分割,为什么不这样做?

String[] line = parse.split(" "); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM