【问题标题】:How to get the line number of specific text in string in c#如何在c#中获取字符串中特定文本的行号
【发布时间】:2014-10-04 01:33:03
【问题描述】:

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

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

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

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;
}

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

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/15786612/…
  • @sr28 我不必读取文本文件的特定行。这是通过正确发布的代码完成的,而不是我必须获取包含特定文本的行号
  • 它看起来与您发布的代码非常相似......只是条件略有不同。

标签: c# .net string substring


【解决方案1】:

我知道这已经解决了,但我想将 an alternative 分享给已解决的答案,因为我无法让它用于简单的事情。代码只返回它找到给定字符串的一部分的行号,只需将“包含”替换为“等于”即可。

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;
}

【讨论】:

    【解决方案2】:

    好的,我将简化。如何获取特定文本的行号 在 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;
    }
    

    【讨论】:

    • 好的,我会简化。如何在c#中获取字符串中特定文本的行号
    • StringComparison comparison = StringComparison.CurrentCulture 需要传递什么参数
    • 工作非常感谢!
    • @user3924730:无(可选)或these 之一。例如,如果你想比较不区分大小写(所以"Sample Line" == "sample line"),你可以使用StringComparison.CurrentCultureIgnoreCase。默认是区分大小写的比较。
    • if(line.Equals(lineToFind, comparison)); 我收到一个可能错误的空语句的错误,现在我也没有得到值。为什么?这个函数根本不起作用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多