How to convert string of values into array?

Viewed 554

I have a string, ie 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17. How do I get each value and convert it into an array? [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]. I can't find any suggestions about this method. Can help? I did try using regex, but it just simply remove ',' and make the string into one long sentence with indistinguishable value. Is it ideal to get value before and after ',' with regex and put it into []?

6 Answers

You could use following solution

String dummy = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] dummyArr = dummy.split(",");

Try this to convert string to an array of Integer.

String baseString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] baseArray = baseString.split(",");

int[] myArray = new int[baseArray.length];
for(int i = 0; i < baseArray.length; i++) {
    myArray[i] = Integer.parseInt(baseArray[i]);
}

Java provides method Split with regex argument to manipulate strings.

Follow this example:

String strNumbers= "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] strNumbersArr= strNumbers.split(",");

You can convert an array of string in array of integer with Streams

int[] numbersArr =  Arrays.stream(strNumbersArr).mapToInt(Integer::parseInt).toArray();

Use String.split() and you will get your desired array.

String s1="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";  
String[] mumbers=s1.split(",");    //splits the string based on comma

for(String ss:numbers){  
    System.out.println(ss);  
}  

See the working Example

String csv = "Apple, Google, Samsung";

String[] elements = csv.split(",");
List<String> fixedLenghtList = Arrays.asList(elements);
ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);


//ouput
[Apple, Google, Samsung]

if you want an int array

        String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
        String[] split = s.split(",");
        int[] result = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
Related