2

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 []?

2
  • What about String.split()? Commented Mar 2, 2020 at 9:19
  • Do you want an array of ints ? Commented Mar 2, 2020 at 9:47

6 Answers 6

9

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(",");
Sign up to request clarification or add additional context in comments.

Comments

1

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]);
}

1 Comment

You could also use Streams for that: stackoverflow.com/questions/23057549/… which will be more elegant
1

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();

Comments

0

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);  
}  

1 Comment

using simplified for really great idea here. thanks
0

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]

Comments

0

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.