从 C# 中的字符串末尾删除一定数量的行
Removing a certain amount of lines from the end of a string in C#
所以我在Visual Studio中有一个项目,标签显示多行字符串,我需要从字符串末尾删除特定数量的行,以防止文本跑出标签的边界。我如何在 C# 中执行此操作?
编辑 |抱歉,我的问题措辞似乎有误,我需要删除字符串开头而不是结尾的行。
保留前3位:
text = string.Join("\n", text.Split('\n').Take(3));
在
之后
Sorry ..., I need to delete the lines from the beginning of the string and not the end.
var lines = text.Split('\n');
text = string.Join("\n", lines.Skip(lines.Length - 3));
假设您将多行文本存储在名为 multiLineString 的变量中并且只需要前三行。
multiLineString = label1.Text;
multiLineString = string.Join(Environment.NewLine,
multiLineString.Split(new string[] { Environment.NewLine},
StringSplitOptions.None).Take(3));
label1.Text = multiLineString;
试试这个(只保留第一个 MAX_NUMBER_OF_LINES):
var lines = originalstring.Split(new [] { '\r', '\n' }); // <-- I used constansts instead of Enivronment.NewLine because I'm not sure about input format
lines = lines.Take(MAX_NUMBER_OF_LINES);
var newstring = String.Join(Environment.NewLine, lines);
所以我在Visual Studio中有一个项目,标签显示多行字符串,我需要从字符串末尾删除特定数量的行,以防止文本跑出标签的边界。我如何在 C# 中执行此操作?
编辑 |抱歉,我的问题措辞似乎有误,我需要删除字符串开头而不是结尾的行。
保留前3位:
text = string.Join("\n", text.Split('\n').Take(3));
在
之后Sorry ..., I need to delete the lines from the beginning of the string and not the end.
var lines = text.Split('\n');
text = string.Join("\n", lines.Skip(lines.Length - 3));
假设您将多行文本存储在名为 multiLineString 的变量中并且只需要前三行。
multiLineString = label1.Text;
multiLineString = string.Join(Environment.NewLine,
multiLineString.Split(new string[] { Environment.NewLine},
StringSplitOptions.None).Take(3));
label1.Text = multiLineString;
试试这个(只保留第一个 MAX_NUMBER_OF_LINES):
var lines = originalstring.Split(new [] { '\r', '\n' }); // <-- I used constansts instead of Enivronment.NewLine because I'm not sure about input format
lines = lines.Take(MAX_NUMBER_OF_LINES);
var newstring = String.Join(Environment.NewLine, lines);