Languages
[Edit]
EN

C# / .NET - string contains

11 points
Created by:
JustMike
26120

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join