I have a string with integers in it which are separated by an arbitrary number and kind of symbols, e.g.:
fr365.43//236hu
and want to convert it into a list of the numbers 365, 43 and 236. Is there an easy way to do this?
I have a string with integers in it which are separated by an arbitrary number and kind of symbols, e.g.:
fr365.43//236hu
and want to convert it into a list of the numbers 365, 43 and 236. Is there an easy way to do this?
Using a regular expression you can extract the numbers from the 'dirty' string
var r = new Regex(@"\d+");
var result = r.Matches("fr365.43//236hu");
foreach (Match match in result)
{
Console.WriteLine(match.Value);
}
// outputs 365 then 43 then 236
string s ="fr365.43//236hu";
string result = s.Split(s.Where(x=>!char.IsDigit(x))
.Select(x=>x).ToArray())
.Where(x=>!String.IsNullOrEmpty(x));
The result is an IEnumerable containing the following: 365 43 236
You can use Split
method, if you have more separators you should include them too:
str.Split('.','/').Select(x => x.All(char.IsDigit))
.Select(int.Parse)
.ToList();
The way to extract integer numbers from the string:
var res = Regex.Split(str, @"\D+").Where(x => x.Length > 0).Select(int.Parse).ToArray();