I taking a string input from console
. If I input "abcd" and spilt like this way
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
. But, It should be 4
right ? 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)
...., 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
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("(?!^)")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.