Kona Ahmed
Kona Ahmed

Reputation: 65

Java invalid array size

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 ?

Upvotes: 1

Views: 542

Answers (4)

Sinto
Sinto

Reputation: 930

You can achieve it using regex in split method as follows:

split("(?!^)")

See more details on regex usage.

Upvotes: 0

Baby
Baby

Reputation: 5092

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]

Upvotes: 1

Standin.Wolf
Standin.Wolf

Reputation: 1234

There is an empty space always after a string.So you need to use in your case abcd and a space

Use split("", -1)

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32458

There is an empty String at the end.

Use split("", -1)

...., the array can have any length, and trailing empty strings will be discarded

Upvotes: 2

Related Questions