1

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 ?

2
  • 2
    String.split() is really not the method you should use to get individual characters out of a String. Use charAt() or substring() or toCharArray(). Commented Feb 17, 2014 at 7:59
  • Read about working of method split, u will get your answer...... Commented Feb 17, 2014 at 7:59

4 Answers 4

2

There is an empty String at the end.

Use split("", -1)

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

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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

split("(?!^)")

See more details on regex usage.

Comments

0

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

Use split("", -1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.