0

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:

  • 1
  • 2
  • 3
  • 4
  • 5
2
  • fastest? fastest to code or fastest to execute? unless you have very specific requirements, I'd personally go for the most readable solution. e.g.: The String.Split() might arguably be faster than the regex but the regex solution is way more readable (and reliable IMO, but that's arguable too). Commented Feb 28, 2014 at 7:51
  • Just split the string using Split function. But to remove the special characters or just to get the numeric values you can use regex. Commented Feb 28, 2014 at 7:51

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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. '*', '/', '+'.

Comments

1

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

3 Comments

@Serge-appTranslator Just check the output in demo link.
@Downvoter care to comment? I added a link to working demo also!
Ha, you fixed it while I was typing ;-) FWIW, I am not the downvoter.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.