Wednesday, March 22, 2017

How to convert String into integer array

If the string is something like “12 41 21 19 15 10” and we want an into array, do like follows:

String test = "12 41 21 19 15 10";
// The string to be extracted to an integer array.
String[] intAsString = test.split(" ");
// Splits each space separated integer into a String array.
int[] integers = new int[intAsString.length];
// Creates the integer array.
int i=0;
for (String no : intAsString){
integers[i++] = Integer.parseInt(no);
}



Or if numbers are comma separated:
// String source = "1,2,3,56789,42";
private static int[] getIntsFromString(String source ) {
  String[] integersAsText =  
  source.split(",");
  int[] results = new 
  int[ integersAsText.length ];
  int i = 0;   for ( String textValue :
  integersAsText ) {
  results[i++] = 
  Integer.parseInt( textValue );
  }
  return results ;
}

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete