寻找字符串列表中的下一个匹配项(整数)

问题描述 投票:0回答:2

我在查找字符串列表中的下一个整数匹配时遇到问题,需要考虑其他一些方面:

  • 单个字符串包含不相关的尾随和前导字符
  • 数字的格式为“ D6”示例000042
  • 数字中有空格
  • 列表未排序,但是如果有一种快速的方法可以忽略前导字符,则可能是这样

示例:

  • abc-000001.file
  • aaac-000002.file
  • ab-0002010.file
  • abbc-000003.file
  • abbbc-000004.file
  • abcd-000008.file
  • abc-0000010.file
  • x-9002010.file

用户输入为7 =>下一个匹配的字符串为abcd-000008.file

我的尝试是:

int userInput = 0;
int counter = 0;
string found = String.Empty;
bool run = true;

while (run)
{
    for (int i = 0; i < strList.Count; i++)
    {
        if(strList[i].Contains((userInput + counter).ToString("D6")))
        {
            found = strList[i];
            run = false;
            break;
        }
    }
    counter++;
}

这很糟糕,因为它很慢,并且可能会变成无限循环。但是我真的不知道该怎么做(快速)。

c# string list search numbers
2个回答
0
投票
如果您不希望使用正则表达式,则可以执行以下操作:

List<string> strings = new List<string> { "abc-000001.file", "aaac-000002.file", "ab-0002010.file", "abbc-000003.file", "abbbc-000004.file", "abcd-000008.file" }; int input = 7; var converted = strings.Select(s => new { value = Int32.Parse(s.Split('-', '.')[1]), str = s }) .OrderBy(c => c.value); string result = converted.FirstOrDefault(v => v.value >= input).str; Console.WriteLine(result);


0
投票
您可以使用Regex解析字符串中的数字,并创建一个可以使用Where子句进行搜索的排序集合:

var strings = new[] { "abc-000001.file", "x-000004.file"}; var regP = "\\d{6,}"; // simplest option in my example, maybe something more complicated will be needed var reg = new Regex(regP); var collection = strings .Select(s => { var num = reg.Match(s).Captures.First().Value; return new { num = int.Parse(num), str = s}; }) .OrderBy(arg => arg.num) .ToList(); var userInput = 2; var res = collection .Where(arg => arg.num >= userInput) .FirstOrDefault()?.str; // x-000004.file

P.S。

如何处理900201000000100002010?因为它们有7个字符。是[9002010,10,2010]还是[900201,1,201]?

© www.soinside.com 2019 - 2024. All rights reserved.