Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a character as a separator in a string

Tags:

java

android

I get a response back from the server like this : "Username|Name|AccountType|Organization". Is there a way to use the "|'s" as separators and get each variable separately. I'm guessing I would have to use a for loop.

like image 679
Thunderclap Avatar asked Jan 10 '23 02:01

Thunderclap


2 Answers

you can use String.split with | . It will return a String[] array. For instance

String test = "Username|Name|AccountType|Organization";
for (String token :  test.split("\\|")) {
     Log.i("TEST", token);
 }
like image 123
Blackbelt Avatar answered Jan 12 '23 14:01

Blackbelt


If you use Guava's Splitter class:

List<String> tokens = Splitter.on("|").split("Username|Name|AccountType|Organization");

With Apache Commons' StringUtils class:

String[] tokens = StringUtils.split("Username|Name|AccountType|Organization", '|');

And plain Java Strings:

String[] test = "Username|Name|AccountType|Organization".split("\\|");

PS: no you don't need Guava or Apache Commons just to split a string. But they bring in a lot of really useful stuff that will make your code more robust. Guava is one of the libraries I include in any project.

like image 20
Vincent Mimoun-Prat Avatar answered Jan 12 '23 16:01

Vincent Mimoun-Prat