Parse String into list of items in .NET

2019-09-17 06:20发布

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

4条回答
你好瞎i
2楼-- · 2019-09-17 06:29

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

查看更多
Ridiculous、
3楼-- · 2019-09-17 06:35

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

查看更多
叛逆
4楼-- · 2019-09-17 06:37

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.

查看更多
叼着烟拽天下
5楼-- · 2019-09-17 06:49

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

查看更多
登录 后发表回答