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

时间:2011-02-09 00:22:22

标签: c# .net string

如何删除字符串中的第一个 n 行?

示例:

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

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

8 个答案:

答案 0 :(得分:16)

您可以使用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"

答案 1 :(得分:12)

如果您需要考虑“\ 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是关于将文本拆分为行的更多详细信息。

答案 2 :(得分:3)

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

答案 3 :(得分:3)

尝试以下方法:

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

答案 4 :(得分:1)

试试这个:

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;
}

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

答案 5 :(得分:1)

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);
}

答案 6 :(得分:0)

尝试以下方法:

    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类的方法。

答案 7 :(得分:0)

能够删除前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;
}