Part 36. String.IndexOf()

String.IndexOf() 


String.IndexOf() is based on the string method. this is method is based on specific index character. the method will return -1 character if the character or string not found.

1. String.IndexOf(char x)

This method will return the zero based index of the string. the given string not found then it return -1.

Case : 1

class Program
    {
        {
            string data = "csharp-tutorial-point";
            if(data.IndexOf("tutorial") !=-1)
            {
                 Console.WriteLine(("string contains tutorial");
            }
             Console.ReadLine();
        }       

    }


Case : 2 
String.IndexOf(char x, int pos1)

This method takes two parameters .char is specify the character to be search and pos1 of type int which specify the position of integer value from where the searching to be started.

class Program
    {
        static void Main(string[] args)
        {
            string data = "csharp-tutorial-point";
            var i = data.IndexOf('a', 4);
            Console.WriteLine("Index Present on :"+i);
               
            Console.ReadLine();
        }

    }
Output

Index Present on :13



 class Program

    {
        {
            string data = "csharp-tutorial-point";
            int i = 0;
            while((i= data.IndexOf('a', i)) !=-1)
            {
                   Console.WriteLine(data.Substring(i));
                i++;
            }
               Console.ReadLine();
        }       

    }


Output 

arp-tutorial-point
al-point:



Case : 3


 class Program

    {
        {
           const string data = "csharp-tutorial-point";
            if (data.IndexOf("tutorial") !=-1)
            {
                  Console.WriteLine("the value found");
            }
            else if (data.IndexOf("chandan") != -1)
            {
                   Console.WriteLine("the value found");
            }
          //Some different method to find 
            var val= data.IndexOf("plus") ! = -1 ? "the value found" : data.IndexOf("chandan") != -1 ?  "the value found":"Not Found";

            System.Console.WriteLine(val);

             Console.ReadLine();
        }       
    }

}

Output :

the value found
------------single line if condition------------
find the value : the value found