【问题标题】:How can I delete the first n lines in a string in C#?如何在 C# 中删除字符串中的前 n 行?
【发布时间】:2026-02-12 12:20:04
【问题描述】:

如何删除字符串中的前 n 行?

例子:

String str = @"a
b
c
d
e";

String output = DeleteLines(str, 2)
//Output is "c
//d
//e"

【问题讨论】:

    标签: c# .net string


    【解决方案1】:

    Get the index of the nth occurrence of a string?(搜索 Environment.NewLine)和子字符串的组合应该可以解决问题。

    【讨论】:

    • 你能把你提到的答案的相关部分粘贴到你的答案中吗?
    【解决方案2】:

    您可以使用 LINQ:

    String str = @"a
    b
    c
    d
    e";
    
    int n = 2;
    string[] lines = str
        .Split(Environment.NewLine.ToCharArray())
        .Skip(n)
        .ToArray();
    
    string output = string.Join(Environment.NewLine, lines);
    
    // Output is 
    // "c
    // d
    // e"
    

    【讨论】:

    • 击败我,但你需要StringSplitOptions.RemoveEmptyEntries,因为 Split 分别解释 \r 和 \n
    • @Marlon - 我不确定删除空条目是否是问题中的要求。我想这不是因为问题集中在线条而不是字符/单词上。
    • 你胆小怕事地把所有的东西都写在一个不可读的行里?称其为正确使用 LINQ? ;)
    【解决方案3】:

    尝试以下方法:

        private static string DeleteLines(string input, int lines)
        {
            var result = input;
            for(var i = 0; i < lines; i++)
            {
                var idx = result.IndexOf('\n');
                if (idx < 0)
                {
                    // do what you want when there are less than the required lines
                    return string.Empty;
                }
                result = result.Substring(idx+1);
            }
            return result;
        }
    

    注意:此方法不适用于极长的多行字符串,因为它不考虑内存管理。如果处理这类字符串,我建议你改变方法使用 StringBuilder 类。

    【讨论】:

    • 为什么不直接找到第 n 个 \n 并从该点开始执行单个子字符串。上面的许多答案都非常低效,我希望这个答案能以简单的方式做到这一点。我看到这是@Lukáš Novotný 的回答(他引用了,但这里没有重复)。
    【解决方案4】:

    尝试以下方法:

    public static string DeleteLines(string s, int linesToRemove)
    {
        return s.Split(Environment.NewLine.ToCharArray(), 
                       linesToRemove + 1
            ).Skip(linesToRemove)
            .FirstOrDefault();
    }
    

    下一个例子:

    string str = @"a
    b
    c
    d
    e";
    string output = DeleteLines(str, 2);
    

    返回

    c
    d
    e
    

    【讨论】:

    • 如果内容有空行,则会在删除时返回错误结果
    【解决方案5】:

    如果您需要考虑“\r\n”和“\r”和“\n”,最好使用以下正则表达式:

    public static class StringExtensions
    {
        public static string RemoveFirstLines(string text, int linesCount)
        {
            var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
            return string.Join(Environment.NewLine, lines.ToArray());
        }
    }
    

    Here 是有关将文本分成行的更多详细信息。

    【讨论】:

      【解决方案6】:

      能够删除前n行或后n行:

      public static string DeleteLines(
           string stringToRemoveLinesFrom, 
           int numberOfLinesToRemove, 
           bool startFromBottom = false) {
                  string toReturn = "";
                  string[] allLines = stringToRemoveLinesFrom.Split(
                          separator: Environment.NewLine.ToCharArray(),
                          options: StringSplitOptions.RemoveEmptyEntries);
                  if (startFromBottom)
                      toReturn = String.Join(Environment.NewLine, allLines.Take(allLines.Length - numberOfLinesToRemove));
                  else
                      toReturn = String.Join(Environment.NewLine, allLines.Skip(numberOfLinesToRemove));
                  return toReturn;
      }
      

      【讨论】:

        【解决方案7】:

        试试这个:

        public static string DeleteLines (string text, int lineCount) {
            while (text.Split('\n').Length > lineCount)
                text = text.Remove(0, text.Split('\n')[0].Length + 1);
            return text;
        }
        

        它可能效率不高,但它非常适合我最近一直在做的小项目

        【讨论】:

        • 您不应该在任何项目中使用这样的拆分,将其声明为变量并重用它。这是一个非常坏的习惯。
        【解决方案8】:
        public static string DeleteLines(string input, int linesToSkip)
        {
            int startIndex = 0;
            for (int i = 0; i < linesToSkip; ++i)
                startIndex = input.IndexOf('\n', startIndex) + 1;
            return input.Substring(startIndex);
        }
        

        【讨论】:

        • 最好在代码中包含一些上下文/解释,因为这会使答案对 OP 和未来的读者更有用(特别是因为这是一个已经有其他几个高质量答案的老问题) .
        最近更新 更多