繁体   English   中英

如何在c#中获取字符串中特定文本的行号

[英]How to get the line number of specific text in string in c#

我有一个包含很多行的字符串。现在根据我的要求,我必须在这个字符串中搜索一个子字符串(文本),并找出该子字符串(文本)在字符串中存在的行号。

一旦我得到行号,我必须阅读该行并了解其中的哪些内容是字符,什么是整数或数字。

这是我用来读取特定行的代码..

private static string ReadLine(string text, int lineNumber)
{
    var reader = new StringReader(text);

    string line;
    int currentLineNumber = 0;

    do
    {
        currentLineNumber += 1;
        line = reader.ReadLine();
    }
    while (line != null && currentLineNumber < lineNumber);

    return (currentLineNumber == lineNumber) ? line : string.Empty;
}

但是如何搜索包含特定文本(子字符串)的行号?

好的,我会简化。如何在 c# 中获取字符串中存在的特定文本的行号

那么你可以使用这个方法:

public static int GetLineNumber(string text, string lineToFind, StringComparison comparison = StringComparison.CurrentCulture)
{
    int lineNum = 0;
    using (StringReader reader = new StringReader(text))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            lineNum++;
            if(line.Equals(lineToFind, comparison))
                return lineNum;
        }
    }
    return -1;
}

我知道这已经解决了而且很旧,但我想分享一个已解决答案的替代方案,因为我无法让它为简单的事情工作。 代码只返回它在给定字符串中找到一部分的行号,以准确地将“包含”替换为“等于”。

public int GetLineNumber(string lineToFind) {        
    int lineNum = 0;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
    while ((line = file.ReadLine()) != null) {
        lineNum++;
        if (line.Contains(lineToFind)) {
            return lineNum;
        }
    }
    file.Close();
    return -1;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM