Languages
[Edit]
EN

C# / .NET - string contains

11 points
Created by:
JustMike
3497

In C# / .NET it is possible to check string existence in following ways.

1. String.Contains method example

string text = "My name is John.";

if (text.Contains("John"))
	Console.WriteLine("Text contains John name.");

Output:

Text contains John name.

2. String.IndexOf method example

string text = "My name is John.";
int index = text.IndexOf("John");

if (index != -1)
	Console.WriteLine("Text contans John name.");

Output:

Text contains John name.

3. String.LastIndexOf method example

string text = "My name is John.";
int index = text.LastIndexOf("John");

if (index != -1)
	Console.WriteLine("Text contans John name.");

Output:

Text contains John name.

4. Regex.IsMatch method example

string text = "My name is John.";
Regex regex = new Regex("John");

if (regex.IsMatch(text))
	Console.WriteLine("Text contans John name.");

Output:

Text contains John name.

5. References

  1. String.Contains Method - Microsoft Docs
  2. String.IndexOf Method - Microsoft Docs
  3. String.LastIndexOf Method - Microsoft Docs
  4. Regex Class - Microsoft Docs
  5. Regex.IsMatch Method - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.