How to Split a String of Space Separated Numbers into Integers

How to split a string of numbers on the white space character and convert to integers

Some smart LINQ answers are already provided, here is my extended step by step solution which also allows to ignore invalid numbers:

//Read input string
Console.Write("Input numbers separated by space: ");
string inputString = Console.ReadLine();
//Split by spaces
string[] splittedInput = inputString.Split(' ');
//Create a list to store all valid numbers
List<int> validNumbers = new List<int>();
//Iterate all splitted parts
foreach (string input in splittedInput)
{
//Try to parse the splitted part
if (int.TryParse(input, out int number) == true)
{
//Add the valid number
validNumbers.Add(number);
}
}
//Print all valid numbers
Console.WriteLine(string.Join(", ", validNumbers));

Convert a String containing space separated numbers into an integer array

In a functional way, using Java 8 streams:

int[] y = Arrays.stream(x.split(" ")).mapToInt(Integer::parseInt).toArray();

How to convert a string filled with numbers to seperate integers in a list?

You can split the string , then convert each elements to int -


>>> s = '12 14 17'

>>> list(map(int,s.split()))
[12, 14, 17]
>>>

split space separated numeric string into a list in Python3

Try this

.split() method returns a list of splitted strings. So you can iterate over it and convert it to a integer

A = '5 2 12 4 29'
B = [int(l) for l in A.split()]
['5', '2', '12', '4', '29']

.split() method will return something like this. But you want them in integers. So you can follow the above method

Split a string of tab separated integers and store them in a vector

The duplicate has some solutions, I would, however, prefer to use a stringstream, something like:

#include <sstream>

//...

vector<int> v;

if (infile.is_open()) // make sure the file opening was successful
{
while (getline(infile, line))
{
int temp;
stringstream ss(line); // convert string into a stream
while (ss >> temp) // convert each word on the stream into an int
{
v.push_back(temp); // store it in the vector
}
}
}

As Ted Lyngmo stated this will store all the int values from the file in the vector v, assuming that the file in fact only has int values, for example, alphabetic characters or integers outside the range of what an int can take will not be parsed and will trigger a stream error state for that line only, continuing to parse in the next line.



Related Topics



Leave a reply



Submit