You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Answer from Java Devil on Stack OverflowYou could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
With the Arrays.stream() alternative as
int [] v = Arrays.stream(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
However much better for parsing bigger chunks of text is
int [] v = Pattern.compile(",\\s+").splitAsStream(line)
.mapToInt(Integer::parseInt)
.toArray();
As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.
See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.
How to convert an array of string integers to an array of number integers
Python: How do I convert an array of strings to an array of numbers? - Stack Overflow
Converting a String array into an int Array in java - Stack Overflow
Converting an array of string to array of int in PHP - Stack Overflow
I know this might be a silly question to ask but how could one covert the following into an array of numbers...
['1,2,6,8,15,16,17,20,22,23,24,25,26,27,30,32,33,34,36']
Use int which converts a string to an int, inside a list comprehension, like this:
desired_array = [int(numeric_string) for numeric_string in current_array]
List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map:
list(map(int, ['1','-1','1']))
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next ▼:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
▼ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
Use array_map i.e.
$array = array_map(function($n) { return (int)$i; }, $array);
So Ed-Heal already sent a really good answer, and more efficient, but I will post one with a for loop just to explain the process:
$stringArray = array("2","5"); // We set up the string array
var_dump($stringArray);
// We loop through the array:
for ($i = 0; $i<sizeof($stringArray); $i++) {
// We set the value at the index $i to an integer.
$stringArray[$i] = intval($stringArray[$i]);
}
var_dump($stringArray);
The output of the code above would be as follows
array(2) { [0]=> string(1) "2" [1]=> string(1) "5" }
array(2) { [0]=> int(2) [1]=> int(5) }
So what does this code do? Well we loop through the array, we grab every value and change it with a integer with the function intval().
Oh and please, don't capsize your question's title.
Given an array you can use the Array.ConvertAll method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
EDIT: to convert to array
int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();
This should do the trick:
var asIntegers = arr.Select(s => int.Parse(s));