Convert Comma Separated String of Ints to Int Array

Convert comma separated string of ints to int array

You should use a foreach loop, like this:

public static IEnumerable<int> StringToIntList(string str) {
if (String.IsNullOrEmpty(str))
yield break;

foreach(var s in str.Split(',')) {
int num;
if (int.TryParse(s, out num))
yield return num;
}
}

Note that like your original post, this will ignore numbers that couldn't be parsed.

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

return (str ?? "").Split(',').Select<string, int>(int.Parse);

Convert comma separated list of integers into an array

You want one line? Use LINQ:

int[] cols = sizes.Split(',').Select(x => int.Parse(x)).ToArray();

Add using System.Linq; at the top of the file to make it work.

Without LINQ you'd need a loop:

var source = sizes.Split(',');
var cols = new int[source.Length];
for(int i = 0; i < source.Length; i++)
{
cols[i] = int.Parse(source[i]);
}

Converting comma-separated string of single-quoted numbers to int array


  $arr = explode (",", str_replace("'", "", $str));
foreach ($arr as $elem)
$array[] = trim($elem) ;

How to put string elements separated by commas into an int array?

Here is an example that uses vectors, std::replace, and std::istringstream:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

std::vector<int> convertToIntArray(std::string input)
{
std::replace(input.begin(), input.end(), ',', ' ');

std::istringstream stringReader{ input };

std::vector<int> result;

int number;
while (stringReader >> number)
{
result.push_back(number);
}

return result;
}

int main()
{
std::string testString = "5,6,13,4,14,22";

std::vector<int> newArray = convertToIntArray(testString);

for (int i = 0; i < newArray.size(); ++i)
{
std::cout << newArray[i] << " ";
}
}

Convert comma delimited string to int array

Not sure I understand, but if you mean you want to convert them back to a comma-separated string, you could do something like this:

string nums = string.Join(",", Array.ConvertAll(s.Split(','), int.Parse));

String with Comma separated numbers to array of integer in javascript

I would recommend this:

var array;
if (string.length === 0) {
array = new Array();
} else {
array = string.replace(/, +/g, ",").split(",").map(Number);
}

Swift: safely convert list of comma-separated numbers in a string to an array of Ints

Instead of using ! to force unwrap, use flatMap to ignore components that cannot be converted to Int:

func get_numbers() -> Array<Int> {
return self.numbers_as_csv_string!
.components(separatedBy: ",")
.flatMap {
Int($0.trimmingCharacters(in: .whitespaces))
}
}

Sample results:

1           => [1]
1,2,3 => [1,2,3]
1,5,10 => [1,5,10]

nil => []
1,,2,3 => [1,2,3]
1,Z,10 => [1,10]


Related Topics



Leave a reply



Submit