Reputation: 7475
I have the following string and would like to convert it to string array
String singleArray = "[501]"
String multipleArray = "[1,501,634]"
I would like to get List<String>
from that,
the thing is sometimes it can be a single value
and sometimes it can be multiple value seperate by comma.
I tried to use Arrays.asList(multipleArray)
but it didn't work.
Any suggestions?
Upvotes: 3
Views: 4612
Reputation: 7052
[
and ]
from the beginning and ending using substring
.split rest of the string according to the occurrence of ,
.
String[] arr = multipleArray.substring(
1, multipleArray.length()-1).split(",");
then use the array to make a list.
List<String> list=Arrays.asList(arr);
Upvotes: 1
Reputation: 44854
How about
String arr [] = str.replace("[", "").replace ("]", "").split (",");
And then as per your knowledge, you can use the array to create a List using
Arrays.asList(arr);
Note
As noted by Bas.E, my solution works upon the data as per your example.
Upvotes: 7
Reputation: 62874
[
and ]
characters.,
.For example:
String input = "[1,501,634]";
String[] result = input.substring(1, input.length() - 1).split(",");
List<String> asList = Arrays.asList(result);
Upvotes: 9
Reputation: 168623
Remove the leading and trailing square brackets:
String removedBrackets = multipleArray.replaceAll( "^\\[|\\]$", "" );
or
String removedBrackets = multipleArray.substring( 1, multipleArray.length() - 1 );
Then split the string on the commas:
String[] arrayOfValues = removedBrackets.split( "," );
Then convert it to a list:
List<String> listOfValues = Arrays.asList( arrayOfValues );
Upvotes: 1
Reputation: 368
trim it from side brackets
array = array.substring(1,array.length()-1);
then split and convert to array
String[] arrayStringArray = array.split(",");
and if wanted, make it a List
List<String> arrayStringList = Arrays.asList(arrayStringArray);
Upvotes: 0