What is the fastest way (fastest to execute) to parse the following String into a list of Integers values?
I need the values that are specified between the # # marks.
"#1#+#2#+#3#*1.23+#4#/2+#5#"
The above String should create a list of Integers:
Use regular expressions...
var input = "#1#+#2#+#3#*1.23+#4#/2+#5#";
var matches = Regex.Matches(input, "#(.*?)#")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
matches.ForEach(Console.WriteLine);
Fiddle: http://dotnetfiddle.net/GMqhXZ
Use string.Split
to split your values into an array of strings, and then parse them with int.Parse
for integers or double.Parse
for floating-point values.
If that is your input, you may have to also call Trim
on your strings with the characters you want to remove, e.g. '*', '/', '+'
.
May be this?
var array = Regex.Matches("#1#+#2#+#3#*1.23+#4#/2+#5#", @"(?<=#)\d+(?=#)")
.Cast<Match>()
.Select(x => x.Value)
.ToArray();
This checks whether #
comes before and after a number, if yes matches it.
Here is the ideone demo
The most readable solution would be something like
string text = "#1#+#2#+#3#*1.23+#4#/2+#5#";
foreach (string fragment in text.Split('#'))
{
int number;
if (int.TryParse(fragment, NumberStyles.Integer, CultureInfo.InvariantCulture, out number))
{
Console.WriteLine(number);
}
}
Maybe a faster implementation can be found - but if you do not have to parse several million numbers, I would prefer a readable solution.