سؤال

here's the code that i am using to split the string

str = "1234".split("") ; 
System.out.println(str.length) ; //this gives 5

there is an extra whitespace added just before 1 i.e str[0]=" " How to split this string without having the leading whitespace.

هل كانت مفيدة؟

المحلول

Try this:

char[] str = "1234".toCharArray();
System.out.println(str.length) ;

نصائح أخرى

You are not actually getting a leading whitespace element, you are getting a leading empty string, as can be seen from printing the whole array:

System.out.println(java.util.Arrays.toString("1234".split("")));

Output:

[, 1, 2, 3, 4]

The rationale for that behavior is the fact that "1234".indexOf("") is 0. I.e., the delimiter string matches at the beginning of the searched string, and thus it creates a split there, giving an empty initial element in the returned array. The delimiter also matches at the end of the string, but you don't get an extra empty element there, because (as the String.split documentation says) "trailing empty strings will be discarded".

However, the behavior was changed for Java 8. Now the documentation also says:

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

(Compare String.split documentation for Java 7 and Java 8.)

Thus, on Java 8 and above, the output from the above example is:

[1, 2, 3, 4]

For more information about the change, see: Why in Java 8 split sometimes removes empty strings at start of result array?

Anyway, it is overkill to use String.split in this particular case. The other answers are correct that to get an array of all characters you should use str.toCharArray(), which is faster and more straightforward. If you really need an array of one-character strings rather than an array of characters, then see: Split string into array of character strings.

Use toCharArray() instead....................

if you want to split on "" then should use toCharArray method of string.

String str = "1234";
System.out.println(str.toCharArray().length);

If you are using Java 7 or below, use this:

"1234".split("(?!^)")

I would just do:

str = "1 2 3 4".split(" ");  

Unless of course there's a specific reason why it has to be "1234"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top