if string contains in csharp

To check if a string contains another string in C#, you can use the Contains method of the String class. Here's an example:

main.cs
string sentence = "The quick brown fox jumps over the lazy dog";

if (sentence.Contains("fox"))
{
    Console.WriteLine("The sentence contains the word 'fox'.");
}
else
{
    Console.WriteLine("The sentence does not contain the word 'fox'.");
}
245 chars
11 lines

In this example, the Contains method is used to check if the sentence string contains the word "fox". If it does, it prints a message confirming that the sentence contains the word. Otherwise, it prints a message saying that the sentence does not contain the word.

Note that the Contains method is case-sensitive. If you want to perform a case-insensitive search, you can use the IndexOf method with a StringComparison parameter. Here's an example:

main.cs
string sentence = "The quick brown fox jumps over the lazy dog";

if (sentence.IndexOf("FOX", StringComparison.OrdinalIgnoreCase) >= 0)
{
    Console.WriteLine("The sentence contains the word 'fox'.");
}
else
{
    Console.WriteLine("The sentence does not contain the word 'fox'.");
}
285 chars
11 lines

In this example, the IndexOf method is used with the StringComparison.OrdinalIgnoreCase parameter to perform a case-insensitive search for the word "FOX" in the sentence string. If it finds a match (i.e., the return value is greater than or equal to 0), it prints the corresponding message.

Remember to include the System namespace at the top of your file:

main.cs
using System;
14 chars
2 lines

related categories

gistlibby LogSnag