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.
// 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];
// 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);
}
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 ;
}
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 ;
}
No comments:
Post a Comment