How to Convert a String of Numbers to an Array of Numbers

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.

Convert a string of numbers into an array

You should split the string once and store the array somewhere.

Here you are iterating up to the number of characters in the string, not the number of space-separated numbers.

int [] n1 = new int [numbers.length()];
for(int n = 0; n < numbers.length(); n++) {
n1[n] = Integer.parseInt(numbers.split(" ")[n]);
}

Change to:

String[] parts = numbers.split(" ");
int[] n1 = new int[parts.length];
for(int n = 0; n < parts.length; n++) {
n1[n] = Integer.parseInt(parts[n]);
}

See it working online: ideone

Use Number to convert string to numbers in a copy of an array after using slice and spread operator

The Number constructor converts one value to a number - Number(value)

You're putting in as value a spreaded array from which the first value is taken and converted

Number(...array.splice(2))  // Number('3','4','5','6') => 3

I don't see any good example using the spread operator, since you don't want to get rid of the array structure, but have to iterate the array for converting each element from string to number

  1. For getting rid of the first two entries without altering the original array use .slice() The second argument can be omitted if you want to slice from the index to the end of the array
  2. To keep it short you can directly map on the spliced array using either the Number(v) constructor or by simply adding the + at the front
let array = ['1','2','3','4','5','6']
let numbers1 = array.slice(2).map(str => +str) // [3, 4, 5, 6]
let numbers2 = array.slice(2).map(str => Number(str)) // [3, 4, 5, 6]

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.

Convert string of numbers to array of numbers?

let numbers = ["54321"]
const temp = numbers[0].split('')
const result = temp.map(n => parseInt(n))
console.log(result)

how to convert string values to numbers in a mixed array

NaN === NaN will always return false. To check if element is NaN you need to use isNaN function.

const transData = ["new york", "10.99", "2000"];for(let i = 0; i< transData.length; i++){  if(!isNaN(transData[i])){    transData[i] = +transData[i];  }}console.log(transData)

How to convert a string representation to an array integers?

The easy way is using .map() to create a new array along with using Number to parse each string into numbers.

var str = ["163600", "163601", "166881"];
var result = str.map(Number);
console.log(result);

/*Using `JSON.parse` first if your data is not an string array.*/
console.log(JSON.parse("[\"163600\", \"163601\", \"166881\"]").map(Number));

How do I parse a string of numbers into a array of integers?

I think this will do what you want.

#include "stdafx.h"

#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;

#define MAX 100

int *parse_line(char *line, int *numInts) {
char sNumArray[MAX];
strcpy(sNumArray, line);
int *numbers = (int *) malloc(sizeof(int) * MAX);
char *tokens = strtok(sNumArray, " ");
for (int i = 0; ; i++) {
numbers[i] = atoi(tokens);
tokens = strtok(NULL, " ");
if (tokens == NULL) {
*numInts = i+1;
break;
}
}

return numbers;
}

int main() {
char *line = "10 10 10 4 4 4 9 9 9 2";
int numIntsExtracted = 0;
int *skyline = parse_line(line, &numIntsExtracted);

for (int j = 0; j < numIntsExtracted; ++j) {
printf("%d \n", skyline[j]);
}
return 0;
}

And the output I'm getting after running it.

10
10
10
4
4
4
9
9
9
2

Javascript - Converting string to number in an array of objects

You are over-complicating things; you just need to map each entry in reports to its reportId property and convert that to an integer

let reports = [ 
{reportId: "21", title: "Online", code: "ON" },
{reportId: "11", title: "Retail", code: "RE" },
{reportId: "61", title: "Walk-in", code: "WI" }
]

let ids = reports.map(function (item) {
return parseInt(item.reportId, 10);
});

console.log(ids)

String of numbers to array of numbers

You're almost there, add the type ascription to nums:

let nums: Vec<u32> = ...

and end the method chain with .collect() to turn it into a vector of digits.



Related Topics



Leave a reply



Submit