简体   繁体   English

Java无效的数组大小

[英]Java invalid array size

I taking a string input from console . 我从console获取字符串输入。 If I input "abcd" and spilt like this way 如果我输入“abcd”并像这样溢出

Scanner input = new Scanner(System.in);
String[]stringInput = input.nextLine().toLowerCase().trim().split("");

Suppose, I have entered "abcd" as input, stringInput.length is showing 5 . 假设我输入"abcd"作为输入, stringInput.length显示为5 But, It should be 4 right ? 但是,它应该是4对吗? What's wrong, I am doing here ? 怎么了,我在这儿干什么? Any idea ? 任何想法 ? How can I solve that ? 我怎么解决这个问题?

There is an empty String at the end. 最后有一个空字符串。

Use split("", -1) 使用split("", -1)

...., the array can have any length, and trailing empty strings will be discarded ....,数组可以有任何长度, 尾随空字符串将被丢弃

Using split("") there always be an extra empty element of array at the first index 使用split("")在第一个索引处总是有一个额外的空数组元素

to be sure, you can try: 可以肯定的是,你可以尝试:

System.out.println(Arrays.toString(stringInput));

Output: 输出:

[, a, b, c, d]

在字符串之后总是有一个空的空间。所以你需要在你的情况下使用abcd和空格

Use split("", -1)

You can achieve it using regex in split method as follows: 您可以使用split方法中的regex实现它,如下所示:

split("(?!^)")

See more details on regex usage. 查看有关正则表达式使用的更多详细信息

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

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