bala3569
bala3569

Reputation: 11000

Case insensitive search in a text file

I need a case insensitive search for the following code...

  while ((line = file.ReadLine()) != null)
    {
     if (line.Contains(line2))
     dest.WriteLine("LineNo : " + counter.ToString() + " : " + line);
     counter++;
    }

I have tried like this

if (line.Contains(line2,StringComparer.OrdinalIgnoreCase))

But it doesnt seem fit..Any suggestion??

Upvotes: 1

Views: 2010

Answers (6)

Albireo
Albireo

Reputation: 11085

Edit

Forget my first answer, I misread the question.

You should use String.IndexOf (String, StringComparison):

foreach (String Row in File.ReadLines("Test.txt"))
{
    if (Row.IndexOf("asd", StringComparison.InvariantCultureIgnoreCase) != -1)
    {
        // The row contains the string.
    }
}

Upvotes: 4

Mitch Wheat
Mitch Wheat

Reputation: 300499

One way is to create a string extension method:

if (line.ContainsCaseInsensitive(value))
{
    // ..
}

public static bool ContainsCaseInsensitive(this string source, string find)
{
    return source.IndexOf(find, StringComparison.CurrentCultureIgnoreCase) != -1;
}

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283624

In user-contributed comments on the String.Contains documentation at MSDN, a workaround is provided.

bool contains = str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;

Upvotes: 3

ichen
ichen

Reputation: 512

Use a regular expression (Regex class in .NET) and specify case insensitivity option (part of the constructor).

Upvotes: 1

Jaster
Jaster

Reputation: 8581

Try StringComparer.CurrentCultureIgnoreCase.

Upvotes: 1

Nobody
Nobody

Reputation: 4841

You can convert both sides to upper or lower case using "myString".ToLower();

It's effectively case-insensitive.

Upvotes: -3

Related Questions