when enter the text to find the string i want to ignore the case how to implement that in a context below

public override void Search()
        {
            
            //file = new FileStream(@"C:\username.txt", FileMode.Open, FileAccess.Read);
            
            Console.WriteLine("Input a string ");
            String data = Console.ReadLine();
            sr = File.OpenText(@"C:\username.txt");
            String st = sr.ReadToEnd();
           // How to implement ignore cases 
            
                if (st.Contains(data))
                {
                    Console.WriteLine("Found at position :" + st.IndexOf(data));
                }
                else
                {
                    Console.WriteLine("Not Found");
                }

Thanks,

Dani AI

Generated

Quick answer: prefer the IndexOf overload that takes a StringComparison value instead of lowercasing both strings. ’s ToLower() idea works, but it allocates extra strings and can give different results under different cultures. Using IndexOf(..., StringComparison.OrdinalIgnoreCase) (or CurrentCultureIgnoreCase when you need culture-aware rules) is clearer and faster. See the String.IndexOf overload for details: String.IndexOf with StringComparison.

Example (case-insensitive, returns position):

string content = File.ReadAllText(@"C:\username.txt");
string query = Console.ReadLine();

int pos = content.IndexOf(query, StringComparison.OrdinalIgnoreCase);
if (pos >= 0)
    Console.WriteLine("Found at position: " + pos);
else
    Console.WriteLine("Not Found");

If the file can be large, avoid ReadAllText and search line-by-line to keep memory use low; File.ReadLines streams the file lazily:

int lineNo = 0;
foreach (var line in File.ReadLines(@"C:\username.txt"))
{
    lineNo++;
    int col = line.IndexOf(query, StringComparison.OrdinalIgnoreCase);
    if (col >= 0)
    {
        Console.WriteLine("Found on line {0}, column {1}", lineNo, col + 1);
        break;
    }
}

For pattern searches (regular expressions) use Regex.Match with RegexOptions.IgnoreCase and Regex.Escape for literal input. Note: IndexOf/Match return character indexes (not byte offsets); byte positions depend on file encoding. Also check for null/empty query before searching. For streaming docs see File.ReadLines and for regex see Regex.Match.

Recommended Answers

All 2 Replies

You can do something like this:

if (st.ToLower().Contains(data.ToLower()))

Thanks a million but i got some other solution. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.