我该如何删除字符串中的前n行?
示例:
String str = @"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
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"
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());
}
}
这里有关于将文本拆分成行的更多详细信息。
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
结合获取字符串第n个出现位置的索引(搜索Environment.NewLine)和子字符串应该可以解决问题。
试试这个:
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;
}
虽然可能不是很高效,但对我最近正在开展的小项目来说完全可行
请尝试以下方法:
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;
}
\n
,然后从那个位置开始进行一次子字符串操作呢?上面的很多答案都非常低效,我本来期望有一个简单的方法来解决这个问题。我看到@Lukáš Novotný的回答就是这样做的(他在这里引用了,但没有重复)。 - iCollect.it Ltd具有删除前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 input, int linesToSkip)
{
int startIndex = 0;
for (int i = 0; i < linesToSkip; ++i)
startIndex = input.IndexOf('\n', startIndex) + 1;
return input.Substring(startIndex);
}
StringSplitOptions.RemoveEmptyEntries
,因为 Split 方法会单独解释 \r 和 \n。 - Marlon