CSharp - String String Searching

Introduction

You can search within strings with StartsWith, EndsWith and Contains methods.

These all return true or false:

Demo

using System;
class MainClass{/*  w  w w . j a  v a2 s.  c om*/
   public static void Main(string[] args)
   {
     Console.WriteLine ("this is a test".EndsWith ("test"));      
     Console.WriteLine ("this is a test".Contains ("is"));    
   }
}

Result

StartsWith and EndsWith can accept StringComparison enum or a CultureInfo object to control case and culture sensitivity.

The default is to perform a case-sensitive match using rules applicable to the current culture.

The following code performs a case-insensitive search using the invariant culture's rules:

Demo

using System;
class MainClass/*from ww w. j a va2  s  . c om*/
{
   public static void Main(string[] args)
   {
       bool b = "abcdef".StartsWith ("aBc", StringComparison.InvariantCultureIgnoreCase);
       Console.WriteLine(b);

   }
}

Result

IndexOf returns the first position of a given character or substring or -1 if the substring isn't found:

Demo

using System;
class MainClass{/*from  w  ww .  j a  va 2 s .c  o  m*/
   public static void Main(string[] args){
       Console.WriteLine ("abcde".IndexOf ("cd"));   // 2
   }
}

Result

IndexOf is overloaded to accept a startPosition which is an index from which to begin searching, as well as a StringComparison enum:

Console.WriteLine ("abcde abcde".IndexOf ("CD", 6,
               StringComparison.CurrentCultureIgnoreCase));    // 8

LastIndexOf works backward through the string.

IndexOfAny returns the first matching position of any one of a set of characters:

Demo

using System;
class MainClass/*from   ww w .  ja  v  a 2 s  .  co  m*/
{
   public static void Main(string[] args)
   {
     Console.Write ("ab,cd ef".IndexOfAny (new char[] {' ', ','} ));       // 2
     Console.Write ("pas5w0rd".IndexOfAny ("0123456789".ToCharArray() ));  // 3

   }
}

Result

LastIndexOfAny does the same in the reverse direction.