How to use a character as a separator in a string

I get a response from the server as follows: "Username | Name | AccountType | Organization". Is there any way to use "|" as delimiters and get each variable separately. I assume I will have to use a for loop.

+4
source share
3 answers

Yes, like any other String.split.

Here is a quick example:

public class Stack
{
public static void main(String[] args)
{
    String test = "Username|Name|AccountType|Organization";
    String[] token = test.split("\\|");

    System.out.println(test);
    System.out.println();

    for(int i=0; i<token.length; i++)
    System.out.println(token[i]);

    System.out.println();
}
}

The conclusion will be as follows:

Username|Name|AccountType|Organization

Username
Name
AccountType
Organization
+2
source

you can use String.splitwith |. It will return an array String[]. For instance,

String test = "Username|Name|AccountType|Organization";
for (String token :  test.split("\\|")) {
     Log.i("TEST", token);
 }
+4
source

Guava:

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

StringUtils Apache Commons:

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

Java:

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

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

+3
source

All Articles