【发布时间】:2026-02-12 12:20:04
【问题描述】:
如何删除字符串中的前 n 行?
例子:
String str = @"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
【问题讨论】:
如何删除字符串中的前 n 行?
例子:
String str = @"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
【问题讨论】:
Get the index of the nth occurrence of a string?(搜索 Environment.NewLine)和子字符串的组合应该可以解决问题。
【讨论】:
您可以使用 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
尝试以下方法:
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 并从该点开始执行单个子字符串。上面的许多答案都非常低效,我希望这个答案能以简单的方式做到这一点。我看到这是@Lukáš Novotný 的回答(他引用了,但这里没有重复)。
尝试以下方法:
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
【讨论】:
如果您需要考虑“\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 是有关将文本分成行的更多详细信息。
【讨论】:
能够删除前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;
}
【讨论】:
试试这个:
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;
}
它可能效率不高,但它非常适合我最近一直在做的小项目
【讨论】:
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);
}
【讨论】: