簡體   English   中英

如何根據字符串中的行號搜索文本

[英]How to search text based on line number in string

我有一個功能,它可以搜索字符串中的文本,然后返回包含特定子字符串的行。這是該功能。

private static string getLine(string text,string text2Search)
{
    string currentLine;
    using (var reader = new StringReader(text)) 
    {
        while ((currentLine= reader.ReadLine()) != null) 
        {
            if (currentLine.Contains(text2Search,StringComparison.OrdinalIgnoreCase))
            {
                break;
            }
        }
    }
    return currentLine;
}

現在在我的情況下,我必須開始搜索特定行之后的行,假設這里的第10行意味着必須在10行之后開始在字符串中搜索特定文本。所以我的查詢是如何將其添加到當前函數中。幫我。

您可以將File.ReadLines方法與Skip

var line = File.ReadLines("path").Skip(10)
.SkipWhile(line => !line.Contains(text2Search,StringComparison.OrdinalIgnoreCase))
.First();

您可以這樣在當前代碼中引入一個計數器:

private static string getLine(string text,string text2Search)
{
    string currentLine;
    int endPoint = 10;
    using (var reader = new StringReader(text)) 
    {
        int lineCount = 0;
        while ((currentLine= reader.ReadLine()) != null) 
        {
            if (lineCount++ >= endPoint && 
                currentLine.Contains(text2Search,StringComparison.OrdinalIgnoreCase))
            {
                return currentLine;
            }
        }
    }
    return string.Empty;
}

或者,使用當前代碼將所有行添加到列表中,然后您便可以在其中使用Selmans答案。

String.Contains沒有使用StringComparison.OrdinalIgnoreCase的重載

var match = text.Split(new char[]{'\n','\r'})
            .Skip(10)
            .FirstOrDefault(line=>line.IndexOf("", StringComparison.OrdinalIgnoreCase)>=0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM