Languages
[Edit]
EN

C# / .NET - find text in string

0 points
Created by:
Elleanor-Williamson
230

In this article, we would like to show you how to find text in string in C# / .NET.

Quick solution

string sampleString = "ABCD";
string text = "BC";

// returns true if string contains text
Boolean contains = sampleString.Contains(text);
Console.WriteLine(contains);  // True

or

string sampleString = "ABCD";
string text = "BC";

// returns index of the first occurrence of text in string
int index = sampleString.IndexOf(text);
Console.WriteLine(index);  // 1

 

Practical examples

1. String.Contains()

In this example, we use String.Contains() method to check if the string contains text.

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string sampleString = "Dirask is awesome!";
        string text = "is";

        // returns true if string contains text 
        Boolean contains = sampleString.Contains(text);
        Console.WriteLine("contains = " + contains);  // contains = True
    }
}

Output:

contains = True

2. String.indexOf()

In this example, we use String.IndexOf() method to find the index of the first occurrence of text in the string.

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string sampleString = "Dirask is awesome!";
        string text = "is";

        // returns index of the first occurrence of text in string
        int index = sampleString.IndexOf(text);
        Console.WriteLine("index = " + index);  // 7
    }
}

Output:

index = 7

References

C# / .NET - String (popular problems)

C# / .NET - find text in string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join