Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

Split a string in java

I am getting this string from a program

[user1, user2]

I need it to be splitted as

String1 = user1
String2 = user2

Upvotes: 2

Views: 371

Answers (6)

WhiteFang34
WhiteFang34

Reputation: 72039

You could do this to safely remove any brackets or spaces before splitting on commas:

String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"

Upvotes: 8

Try the String.split() methods.

Upvotes: 2

Boro
Boro

Reputation: 7943

From the input you are saying I think you are already getting an array, don't you?

String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output

Thus having this array you can get them using their index.

String user1 = users[0];
String user2 = users[1];

If you in fact are working with a String then proceed as, for example, @WhiteFang34 suggests (+1).

Upvotes: 0

Gnanz
Gnanz

Reputation: 1873

From where you are getting this string.can you check the return type of the method.

i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.

Upvotes: 0

oliholz
oliholz

Reputation: 7507

Try,

            String source = "[user1, user2]";
            String data = source.substring( 1, source.length()-1 );

            String[] split = data.split( "," );

            for( String string : split ) {
                System.out.println(string.trim());
            }

Upvotes: 5

Ankit
Ankit

Reputation: 2753

This will do your job and you will receive an array of string.

    String str = "[user1, user2]";
    str = str.substring(1, str.length()-1);
    System.out.println(str);
    String[] str1 = str.split(",");

Upvotes: 2

Related Questions