Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android String.split("") returning extra element

Tags:

java

android

I am trying to split a word into its individual letters.

I tried both String.split("") and String.split("|") however when I split a word it is creating a extra empty element. Example:

    word = "word";
    int n = word.length();
    Log.i("20",Integer.toString(n));
    String[] letters = word.split("|");
    Log.i("25",Integer.toString(letters.length));

The output in the Android Monitor is:

07-21 15:50:23.084 5711-5711/com.strizhevskiy.movetester I/20: 4
07-21 15:50:23.085 5711-5711/com.strizhevskiy.movetester I/25: 5

I put the individual letters into TextView blocks and I can actually see an extra empty TextView.

When I test these methods in my regular Java it outputs the expected answer: 4.

I am almost tempted to think this is an actual bug in Android's implementation of the method.

like image 678
Aleksandr Strizhevskiy Avatar asked Jul 11 '26 03:07

Aleksandr Strizhevskiy


1 Answers

I am thinking you want to do this:

public Character[] toCharacterArray( String s ) {

   if ( s == null ) {
       return null;
   }

   int len = s.length();
   Character[] array = new Character[len];
   for (int i = 0; i < len ; i++) {
      array[i] = new Character(s.charAt(i));
   }

   return array;
}

Instead of splitting a word without delimiters?

I hope this helps!

like image 88
Eenvincible Avatar answered Jul 14 '26 16:07

Eenvincible



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!