How to Split String into Array as Integers

How to split a string into an integer array?

If Java 8 you could use a Stream:

"A sequence of elements supporting sequential and parallel aggregate
operations."

Observe:

import java.util.Arrays;
import java.util.stream.Stream;

class Main {
public static void main(String[] args) {
String numbersString = "12345";

int[] numbersIntArray = Stream.of(numbersString.split("")).mapToInt(Integer::parseInt).toArray();

System.out.println(Arrays.toString(numbersIntArray)); // [1, 2, 3, 4, 5]
}
}

How to split() a string to an array of integers

One option is using the Number constructor which returns a number or NaN:

var res = q.split(',').map(el => {
let n = Number(el);
return n === 0 ? n : n || el;
});

// > "The, 1, 2, Fox, Jumped, 3.33, Over, -0"
// < ["The", 1, 2, " Fox", " Jumped", 3.33, " Over", -0]

edit: If the above condition is confusing you can replace it with the following condition which was suggested by Bergi:

return isNaN(n) ? el : n;

In case that you want to trim the string elements you can also use the String.prototype.trim method:

return isNaN(n) ? el.trim() : n;

Swift 3: Split string into Array of Int

Use this

let stringNumbers = "1 2 10"
let array = stringNumbers.components(separatedBy: " ")
let intArray = array.map { Int($0)!} // [1, 2, 10]

convert string into array of integers

You can .split() to get an array of strings, then loop through to convert them to numbers, like this:

var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers

The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:

for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); } 

Split a string into an integer array in C

A function with the signature implied in your post is not possible in C, because a function cannot return a dynamically-sized array. Two choices are possible here:

  • Pass an array and the max count into parseString, or
  • Return a pointer representing a dynamically allocated array, along with its actual size.

The first approach limits the size of the array to some number established by the caller; the second approach comes with a requirement to deallocate the array once you are done with it.

The function that follows the first approach would look like this:

void parseString(int data[], size_t maxSize);

The function that follows the second approach would look like this:

int *parseString(size_t *actualSize);

or like this:

void parseString(int ** data, size_t *actualSize);

The second case can be used to combine the two approaches, although the API would become somewhat less intuitive.

As for the parsing itself, many options exist. One of the "lightweight" options is using strtol, like this:

char *end = str;
while(*end) {
int n = strtol(str, &end, 10);
printf("%d\n", n);
while (*end == ',') {
end++;
}
str = end;
}

Demo.

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 split a numeric string and then store it in an int array in c?

You have to convert string to int using strtol for example:

   char *p = strtok(b," ");
while( p != NULL)
{
arr[i++] = strtol(p, NULL, 10); // arr[i++] = p is wrong, because p is a string not an integer value
p = strtok(NULL," ");
}

When you print the value of array, use %d for integer value instead of %s. You use init_size is wrong. Because in the string, it has some space character. Your printing part should change to:

    for(int j = 0; j < i; j++)
printf("%d\n", arr[j]);

The complete code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char b[] = "1 2 3 4 5";
int init_size = strlen(b);
int arr[init_size];
int i = 0;

char *p = strtok(b," ");
while( p != NULL)
{
arr[i++] = strtol(p, NULL, 10);
p = strtok(NULL," ");
}

for(int j = 0; j < i; j++)
printf("%d\n", arr[j]);

return 0;
}


Related Topics



Leave a reply



Submit