Reputation: 11
I have string like this:
string mystring = "123456"
And I want to split two by two to 12 34 56.
Pseudocode:
var list = new List<int>();
foreach(var e in something){
string mystring ="123456";
var split = ...
// convert the splitted string
list.Add(convertedString);
}
How I can do this?
Upvotes: 1
Views: 397
Reputation: 2567
You can try this,
var str = "123456";
var intList = Enumerable.Range(0, str.Length / 2)
.Select(i => Convert.ToInt32( string.Concat(str.Skip(i * 2).Take(2)))).ToList();
if you console log the result:
foreach(var e in intList)
{
Console.WriteLine(e);
}
Output list will contain elements like `12, 34, 56 respectively.`
Upvotes: 0
Reputation: 81533
Another way which may or may not be easier to understand
public static IEnumerable<int> SplitInts(this string source)
{
for (var i = 0; i < source.Length; i += 2)
yield return int.Parse(source.Substring(i, Math.Min(2, source.Length - i)));
}
Usage
var test = "23456";
foreach (var item in test.SplitInts())
Console.WriteLine(item);
Output
23
45
6
Upvotes: 1