c# - 在 C# 中的数组中搜索字符串的开头

标签 c# .net arrays string

我有一个包含很多路径的列表。我有一个特定的路径,我想对照这个列表检查是否有任何路径使用这个路径,即:

f.StartsWith(r.FILENAME) && f != r.FILENAME

最快的方法是什么?

编辑:从下面的答案中完成功能:

static bool ContainsFragment(string[] paths, string fragment)
{
    // paths **must** be pre-sorted via Array.Sort(paths);
    if (paths.Length == 0) return false;
    int index = Array.BinarySearch(paths, fragment);
    if (index >= 0 && index+1 < paths.Length)
    { //we found it 
        if (paths[index + 1].StartsWith(fragment) &&
            paths[index + 1].EndsWith(".manifest"))
        {
            return true;
        }
    }
    return false;
}

最佳答案

最快的方法可能是二分查找:

static bool ContainsFragment(string[] paths, string fragment)
{
    // paths **must** be pre-sorted via Array.Sort(paths);
    if (paths.Length == 0) return false;
    int index = Array.BinarySearch(paths, fragment);
    // we want the index of the *next highest* path
    if (index < 0) { // no match
        index = ~index; 
    } else { // exact match
        index++; // for strict substring (non-equal)
    }
    return index < paths.Length && paths[index].StartsWith(fragment);
}

但是如果你只做几次,那么对数组进行排序的成本将超过任何好处;在这种情况下,只需扫描数组 - 使用 LINQ 等,或者只是:

bool found = false;
for(int i = 0 ; i < paths.Length ; i++) {
    if(paths[i].StartsWith(fragment) &&
          paths[i].Length != fragment.Length)
    {
        found = true;
        break;
    }
}

关于c# - 在 C# 中的数组中搜索字符串的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/540947/

相关文章:

c# - 以最快的方式从有条件的列表中删除

c# - 关于引用/集合/值类型的另一个 C# 问题

php - 重新排序多维数组,以便每 4 行出现具有特定列值的行

javascript - 为什么 JavaScript 允许将数组和函数存储在一个变量中?

c# - 使用 .NET 通过网络连接两个程序

c# - Lambda 表达式对比不同的对象

c# - Xamarin.Forms MVVM TapGestureRecognizer

.net - 使用绑定(bind)数据和转换器对 datagrid 列进行排序

c - 基本 C 循环比较

c# - 制作自己的 Windows 8 应用程序主题