繁体   English   中英

在Java中拆分字符串,

[英]Splitting a string in Java,

我试图将一个字符串拆分成一个字符串数组,但是当它拆分字符串时,只有第一部分,在拆分之前,在[0]插槽中的数组中,但是[1]或更晚的内容中没有任何内容。 这也会在尝试输出拼接时返回java异常错误[1]

import java.util.Scanner;

public class splittingString
{

    static String s;


    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the length and units with a space between them");
        s = input.next();
        String[] spliced = s.split("\\s+");
        System.out.println("You have entered " + spliced[0] + " in the units of" + spliced[1]);
    }

}

你应该使用: -

input.nextLine()

目前,您正在使用next将返回空格

input.next()读取单个单词而不是整行(即将在第一个空格处停止)。 要读取整行,请使用input.nextLine()

假设您的输入为12 34 ,则s变量的内容为12 ,而不是12 34 您应该使用Scanner.nextLine()来读取整行。

问题不在于split()函数调用。 相反,问题在于您用于从控制台读取输入的功能。

next()只读取您键入的第一个单词(在遇到的第一个空格后基本上不读取)。

而是使用nextLine() 它会读取整行(包括空格)。

这里更正的代码:

import java.util.Scanner;

public class StringSplit {

    static String s;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out
                .println("Enter the length and units with a space between them");
        s = input.nextLine();
        String[] spliced = s.split("\\s+");
        System.out.println("You have entered " + spliced[0]
                + " in the units of" + spliced[1]);

    }

}

暂无
暂无

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

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