Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.Split split everyone

Tags:

java

android

I want to split a String to Array.
I use the method string.split.

My Code

            list = "Toni Mustermann|Jenny Mustermann|Jorge Mustermann";
            kinderarray = list.split("|");

But this is the output (Android): https://i.sstatic.net/QHmvT.png

https://i.sstatic.net/QHmvT.png

The Code:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Wähle ein Kind");
    builder.setItems(kinderarray, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            selectkind = kinderarray[item];
            Toast.makeText(MainActivity.this, selectkind, Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
like image 534
ternes3 Avatar asked Jul 26 '26 23:07

ternes3


1 Answers

String#split uses a regular expression as its argument. The pipe character | is a special character used to denote OR in the expression. It should be escaped

kinderarray = list.split("\\|");

otherwise the OR expression will cause the String to be split into a String array based on its individual characters complete with initial empty String element.

This has remained the same for the next year's Java 8 release so is unlikely to change.

like image 192
Reimeus Avatar answered Jul 28 '26 15:07

Reimeus



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!