C#从字符串中的特定行号读取文本 [英] C# read text from a certain line number from string
问题描述
让我说我有一个包含两行的字符串
[] =新行,如enviermentail行,它不是字符串的一部分,而是字符串集合的一个示例
lets say i got a string which has 2 lines in it
[] = the new line like enviermentail line and it not part of the string but is an example of collection of strings
StringCollection text = "That [] Hat";
因此您可以看到有2行,"That"在第1行,"Hat"在第2行
我希望能够阅读第2行,例如
so as you can see there are 2 lines, "That" is on line 1 and "Hat" is on line 2
I want to be able to read line 2, for example
this.text = text.line2.tostring();
和text.line2.tostring();将是帽子"
所以我想知道是否有人可以帮助我实现这一目标?
and text.line2.tostring(); will be "Hat"
so i was wondering if some one can help me achieve this goal?
推荐答案
尝试类似的方法.
try something like this.
static void Main(string[] args)
{
StringCollection TEXT = new StringCollection();
TEXT.Add("That");
TEXT.Add(Environment.NewLine);
TEXT.Add("Hat");
TEXT.Add(Environment.NewLine);
TEXT.Add("Hat2");
int i = 0;
foreach (string str in TEXT)
{
if (str==Environment.NewLine)
i=i+1;
else if(i==2)
Console.WriteLine(str);
}
Console.Read();
}
在这里i == 2表示我想要第二行.它将返回我Hat2
如果我给i == 1,它将给我第一行.它将返回我帽子
here i==2 means i want 2nd line..it will return me Hat2
if i give i==1 it will give me 1st line..it will return me Hat
string GetLine(string text, int lineNo)
{
string[] lines = text.Replace("\r","").Split('\n');
return lines.Length >= lineNo ? lines[lineNo-1] : null;
}
您的问题有点不清楚:
-您的[]
似乎不是真实的,而对于\n
等,是正确的(请参见下文)?
-线是否需要去除开头和结尾的空白?
-是否需要处理\r\n
,\n\r
,\r
,\n
?
BTW:请参见以C#进行转义:字符,字符串,字符串格式,关键字,标识符 [ ^ ]用于在字符串中进行转义.
解决方案可能是:
Your question is a bit unclear:
- your[]
seems not to be real, but rather for\n
, etc, correct (see below)?
- do the lines need to have stripped off the leading and trailing white spaces?
- does it need to handle\r\n
,\n\r
,\r
,\n
?
BTW: See Escaping in C#: characters, strings, string formats, keywords, identifiers[^] for escapes in a string.
A solution may be:
// split at new lines, remove empty lines, remove leading and trailing white spaces
public static string[] GetLines(string fullText)
{
return fullText.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim())
.ToArray();
}
干杯
安迪
Cheers
Andi
这篇关于C#从字符串中的特定行号读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!