简体   繁体   English

在Java中拆分字符串,

[英]Splitting a string in Java,

I am trying to split a string into a string array, but when it splits the string only the first part, before the split, is in the array in the [0] slot, but nothing is in [1] or later. 我试图将一个字符串拆分成一个字符串数组,但是当它拆分字符串时,只有第一部分,在拆分之前,在[0]插槽中的数组中,但是[1]或更晚的内容中没有任何内容。 This also returns a java exception error when it tries to output spliced[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]);
    }

}

You should use: - 你应该使用: -

input.nextLine()

Currently, you are using next which will return space delimeted 目前,您正在使用next将返回空格

input.next() reads a single word not a whole line(ie will stop at the first space). input.next()读取单个单词而不是整行(即将在第一个空格处停止)。 To read a whole line use input.nextLine() . 要读取整行,请使用input.nextLine()

Assuming your input is 12 34 , the content of the s variable is 12 , not 12 34 . 假设您的输入为12 34 ,则s变量的内容为12 ,而不是12 34 You should use Scanner.nextLine() to read whole line. 您应该使用Scanner.nextLine()来读取整行。

The problems is not with the split() function call. 问题不在于split()函数调用。 Rather the problem is with the function that you are using to read the input from the console. 相反,问题在于您用于从控制台读取输入的功能。

next() only reads the first word that you type (basically does not read after the first space it encounters). next()只读取您键入的第一个单词(在遇到的第一个空格后基本上不读取)。

Instead use nextLine() . 而是使用nextLine() It would read the whole line (including spaces). 它会读取整行(包括空格)。

Here the corrected code: 这里更正的代码:

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