user3924730
user3924730

Reputation: 183

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

I have a string which contains so many lines in it.Now as per my requirement i have to search a substring(text) into this string and find out the line number in which this substring(text) exists in the string.

Once i will get the line number i have to read that line and get to know Which contents in it is Character and what is integer or digits.

This is the code that i am using to read a specific line ..

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

But how to search the line number which contain specific text(substring)?

Upvotes: 2

Views: 10176

Answers (2)

John M.
John M.

Reputation: 76

I know this is already solved and old but I want to share an alternative to the solved answer because I couldn't get it to work for simple things. The code just returns the line number where it founds a part of the string given, to have the exact one just replace "Contains" with "Equals".

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460068

OK i will simplify.How to get line number of a specific text present in a string in c#

Then you could use this method:

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

Upvotes: 4

Related Questions