String Array to Int Array Conversion

Converting String Array to an Integer Array

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.

How to convert a string of numbers to an array of numbers?

My 2 cents for golfers:

b="1,2,3,4".split`,`.map(x=>+x)

backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :

function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call

I hope it is a bit more clear.

How to convert a string array to an int array?

Split the String into an array first.

String[] stringArray = "114 214 219".split(" ");

Then in the loop you can access that array:

courseNumbers[i] = Integer.parseInt(stringArray[i])

Convert string array to integer array

Use map() and parseInt()

var res = ['2', '10', '11'].map(function(v) {  return parseInt(v, 10);});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')

Convert integer array to string array in JavaScript

You can use map and pass the String constructor as a function, which will turn each number into a string:

sphValues.map(String) //=> ['1','2','3','4','5']

This will not mutate sphValues. It will return a new array.

Converting String array to Integer Array

You're trying to read a string as if it were an array. I assume you're trying to go through the string one character at a time. To do that, use .charAt()

private int[] convert(String string) {
int number[] = new int[string.length()];

for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string.charAt(i)); //Note charAt
}
return number;
}

If you expect the string to be an array of strings, however, you left out the array identifier in the function prototype. Use the following corrected version:

private int[] convert(String[] string) { //Note the [] after the String.
int number[] = new int[string.length()];

for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string[i]);
}
return number;
}

Convert String to int array in Java the fast way

Using String.split() is by far the most efficient when you want to split by a single character (a space, in your case).

If you are aiming for maximal efficiency when splitting by spaces, then this would be a good solution:

List<Integer> res = new ArrayList<>();
Arrays.asList(kraft.split(" ")).forEach(s->res.add(Integer.parseInt(s)));
Integer[] result = res.toArray(new Integer[0]);

And this works for any number of numbers.

How to Convert an String array to an Int array?

If you are using Java8 than this is simple way to solve this issue.

List<?> list = Arrays.asList(indexNumber.split(" "));
list = list.stream().mapToInt(n -> Integer.parseInt((String) n)).boxed().collect(Collectors.toList());

In first Line you are taking a generic List Object and convert your array into list and than using stream api same list will be filled with equivalent Integer value.

convert string array to integer array in php

You can use array_map

$TaxIds = array_map(function($value) {
return intval($value);
}, $TaxIds);


Related Topics



Leave a reply



Submit