How can I check if a string exists in another string

Hope somebody can help me. I am just learning C# and I have a simple question.

I have a variable and I would like to check if that exists in another string. Something like

if ( test contains "abc" ) {

}

Is there an easy way to do this in C#


Solution 1:

Use String.Contains:

if (stringValue.Contains(anotherStringValue))
{  
    // Do Something // 
}

Solution 2:

IndexOf() function will do the work...
It will return -1 if the string does not exist

Solution 3:

string MainString = "String Manipulation"; 
string SearchString = "pul"; 
int FirstChr = MainString.IndexOf(SearchString); 

This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

you can also use Contains(), Contains is an instance method on the string type, which means you can call it on a specific string in your program. It has a bool result, which is true if the parameter is found, and false if it is not found.

using System;

class Program
{
    static void Main()
    {
    Test("Dot Net Perls");
    Test("dot net perls");
    }

    static void Test(string input)
    {
    Console.Write("--- ");
    Console.Write(input);
    Console.WriteLine(" ---");
    //
    // See if the string contains 'Net'
    //
    bool contains = input.Contains("Net");
    //
    // Write the result
    //
    Console.Write("Contains 'Net': ");
    Console.WriteLine(contains);
    //
    // See if the string contains 'perls' lowercase
    //
    if (input.Contains("perls"))
    {
        Console.WriteLine("Contains 'perls'");
    }
    //
    // See if the string contains 'Dot'
    //
    if (!input.Contains("Dot"))
    {
        Console.WriteLine("Doesn't Contain 'Dot'");
    }
    }
}

check C# String Functions and Manipulation for anything about strings.

Solution 4:

using String.Contains(...) may not be a good idea.

String.Contains(...) does an ordinal case-sensitive comparison. So, be careful about case matching.

ofcourse you can use ToLower() or ToUpper() before you check