IndexOf 无法正确识别行是否以值开头

本文关键字:是否 开头 识别 IndexOf | 更新日期: 2023-09-27 18:34:34

如果第一个单词与我拥有的变量匹配,如何从文本文件中删除整行?

我目前正在尝试的是:

List<string> lineList = File.ReadAllLines(dir + "textFile.txt").ToList();
lineList = lineList.Where(x => x.IndexOf(user) <= 0).ToList();
File.WriteAllLines(dir + "textFile.txt", lineList.ToArray());

但我无法删除它。

IndexOf 无法正确识别行是否以值开头

你唯一的错误是你用indexOf检查<= 0,而不是= 0。

当字符串不包含搜索的字符串时,返回 -1。

<= 0 表示以 开头或不包含

=0 表示以

此方法将逐行读取文件,而不是一次读取所有文件。 另请注意,此实现区分大小写。

它还假定您不受前导空格的影响。

using (var writer = new StreamWriter("temp.file"))
{
    //here I only write back what doesn't match
    foreach(var line in File.ReadLines("file").Where(x => !x.StartsWith(user)))
        writer.WriteLine(line);  // not sure if this will cause a double-space ?
}
File.Move("temp.file", "file");

你非常接近,String.StartsWith处理得很好:

// nb: if you are case SENSITIVE remove the second argument to ll.StartsWith
File.WriteAllLines(
    path,
    File.ReadAllLines(path)
        .Where(ll => ll.StartsWith(user, StringComparison.OrdinalIgnoreCase)));

对于性能不佳的非常大的文件,请改为:

// Write our new data to a temp file and read the old file On The Fly
var temp = Path.GetTempFileName();
try
{
    File.WriteAllLines(
        temp,
        File.ReadLines(path)
            .Where(
               ll => ll.StartsWith(user, StringComparison.OrdinalIgnoreCase)));
    File.Copy(temp, path, true);
}
finally
{
    File.Delete(temp);
}

另一个需要注意的问题是,如果用户ABCIndexOfStartsWith 都会将ABCABCDEF视为匹配项:

var matcher = new Regex(
    @"^" + Regex.Escape(user) + @"'b", // <-- matches the first "word"
    RegexOptions.CaseInsensitive);
File.WriteAllLines(
    path,
    File.ReadAllLines(path)
        .Where(ll => matcher.IsMatch(ll)));
Use  `= 0` instead of `<= 0`.