Reputation: 302
input (string) : 1 2 3 4 5
I want be :
string line = "1 2 3 4 5";
list<int>list = new list<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
Upvotes: 1
Views: 107
Reputation: 18987
Try this using lambda expression and string split
string line = "1 2 3 4 5";
List<int> list= line.Split(" ").Where(x => x.Trim().length > 0).Select(x => Convert.ToInt32(x)).ToList();
Upvotes: 0
Reputation: 100331
You can split the line on spaces removing empty matches with StringSplitOptions.RemoveEmptyEntries
.
string line = "1 2 3 4 5";
var list = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(n => Convert.ToInt32(n)).ToList();
So the result will have only the numbers then you can convert to int.
Upvotes: 0
Reputation: 6251
You can convert multiple spaces to single ones and then split on ' '
:
var result = Regex.Replace(line, @"\s+", " ").Split(' ').Select(x => int.Parse(x.ToString())).ToList();
Or directly select all numbers by one of these Regexes:
\d{1} --> If the numbers will always consist of a single digit.
\d+ --> If the numbers might contain more than one digit.
Like this:
var result = new List<int>();
foreach (Match i in Regex.Matches(line, @"\d{1}")) // Or the other Regex...
{
result.Add(int.Parse(i.Value));
}
Upvotes: 0
Reputation: 300
You can use the Split method with the StringSplitOptions overload:
string line = "1 2 3 4 5";
char[] delim = {' '};
var list = line.Split(delim, StringSplitOptions.RemoveEmptyEntries)
.Select(i => Convert.ToInt32(i)).ToList();
RemoveEmptyEntries will skip over the blank entries and your output will be:
List<Int32> (5 items)
1
2
3
4
5
See String.Split Method on MSDN for more info.
Upvotes: 1
Reputation: 27095
You may use a Regular Expression to identify the occurrences of integer numbers within the text. Here's a working example.
This may prove to be much more reliable depending on your scenario, e.g. you could type arbitrary words/text in there, and it would still find all numbers.
The C# code to do this would be as follows:
List<int> FindIntegers(string input)
{
Regex regex = new Regex(@"(\d+)");
List<int> result = new List<int>();
foreach (Match match in regex.Matches(input))
{
result.Add(int.Parse(match.Value));
}
return result;
}
Upvotes: 1