How to search substring and character within a string in C#
4 most popular
functions to search string and character in c#
In this article we will see four most popular and important
string searching function in c#. String handling is very common tasks in any
application in any languages. And
sometimes situation occurs where there is need to search sub string or any
character of string from another string. In below example we will see how to do
same.
1) String begins with and ends with
Sometimes it needed to check whether
a string starts and ends with certain character or not. To do same try to
understand below example.
using System;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
string name = "SouravKayal";
if (name.StartsWith("Sou"))
Console.WriteLine("name begins with \"Sou\"");
if (name.EndsWith("yal"))
Console.WriteLine("name ends with \"yal.\"");
Console.ReadLine();
}
}
}
Here is the output of example.

2 )Find first occurrence
of any character from string
If we want to get first occurrence of any character from a
string we have to use IndexOf() function associate with particular string. Have
a look of below example. Here we are trying to search first occurrence of ‘a’
within name string.
using System;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
string name = "SouravKayal";
int idx;
Console.WriteLine("str: " + name);
idx = name.IndexOf('a');
Console.WriteLine("Index of first 'a': " + idx);
Console.ReadLine();
}
}
}

3) Find occurrence of any character from first
and last
In previous example we have seen
how to detect first occurrence of any character in a string. Here we will see
first and last occurrence of any character on a string. To detect last
occurrence ,we have to use LastIndexOf() function associated with the string.
using System;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
string str1 = "abcxyxabc";
// search string
int idx = str1.IndexOf("a");
Console.WriteLine("Index of first occurrence of a: " + idx);
idx = str1.LastIndexOf("a");
Console.WriteLine("Index of last occurrence of a: " + idx);
Console.ReadLine();
}
}
}
Sample output:

4) Last
occurrence of substring of a string
Like character we can pass
substring too, to detect fast and last occurrence. In below example we will detect last occurrence
of certain string of another string.
using System;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
string name = "abcabc";
int idx;
idx = name.LastIndexOf("abc");
Console.WriteLine("Index of last \"abc\": " + idx);
Console.ReadLine();
}
}
}
Here is sample output:
