When you’re working with software development, dealing with strings is something that comes up all the time. In C#, the language gives us several handy methods to search within strings in a simple and efficient way. Some of the most common ones are StartsWith
, EndsWith
, Contains
, IndexOf
, and LastIndexOf
. In this post, we’ll explore these methods with practical examples from everyday scenarios.
StartsWith
The StartsWith
method is used to check whether a string starts with a specific prefix. It returns a boolean: true
if it finds a match, or false
if it doesn’t. This method comes in handy in situations like input validation or filtering lists.
Imagine you’re building a user registration system where phone numbers must start with a country code. You can use StartsWith
to validate this:
string phoneNumber = "+5511999999999";
if (phoneNumber.StartsWith("+55"))
{
Console.WriteLine("Brazilian phone number.");
}
else
{
Console.WriteLine("Phone number from another country.");
}
If the phone number starts with +55
(which is Brazil’s country code), we know it’s a Brazilian number. Otherwise, it’s from another country.
By default, StartsWith
is case-sensitive. So if your string has uppercase letters and your comparison value doesn’t, it won’t match:
string example = "NextWaveEducation";
bool result = example.StartsWith("nextwave");
Console.WriteLine(result); // False
If you want to ignore letter casing, you can use an overload of StartsWith
that accepts a StringComparison
parameter. Just use StringComparison.OrdinalIgnoreCase
:
string example = "NextWaveEducation";
bool result = example.StartsWith("nextwave", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(result); // True
EndsWith
The EndsWith
method checks if a string ends with a specific suffix. It’s useful for things like checking file extensions or validating formats.
Let’s say your app only allows users to upload image files with .jpg
or .png
extensions. You can use EndsWith
to check this:
string imageFile = "userPhoto.jpg";
if (imageFile.EndsWith(".jpg") || imageFile.EndsWith(".png"))
{
// Save the image.
}
else
{
Console.WriteLine("Invalid file format.");
}
If the file name ends with .jpg
or .png
, it’s accepted. Otherwise, you show a message that the file format isn’t valid.
Contains
The Contains
method checks if a string includes a certain substring. It’s like searching for a specific word or group of characters inside a larger text.
Imagine you’re building a search system that needs to identify whether a product description includes certain keywords. You can use Contains
for that:
string productDescription = "This is a next-gen smartphone with a high-resolution camera.";
if (productDescription.Contains("smartphone"))
{
Console.WriteLine("This product is a smartphone.");
}
else
{
Console.WriteLine("This product is not a smartphone.");
}
IndexOf
The IndexOf
method finds the first occurrence of a character or substring and returns the position (index) where it appears. It’s great for locating a word or validating whether specific characters exist.
Let’s say you want to find where a certain word appears in a sentence:
string text = "Learning about strings at Next Wave Education";
string keyword = "Next";
int index = text.IndexOf(keyword);
Console.WriteLine($"The word '{keyword}' appears at position {index} in the text.");
In this case, IndexOf
looks for "Next"
in the text and stores the starting position of the word in the index
variable.
LastIndexOf
The LastIndexOf
method works just like IndexOf
, but instead of returning the first match, it returns the position of the last one. It’s useful when you want to find the last appearance of a character or word in a string.
Let’s say you want to extract a file name from a full file path:
string fullPath = "C:\\Users\\User\\Documents\\project\\final_report.pdf";
int lastSlashIndex = fullPath.LastIndexOf('\\');
string fileNameWithExtension = fullPath.Substring(lastSlashIndex + 1);
Console.WriteLine(fileNameWithExtension);
Here, LastIndexOf
finds the position of the last backslash (\
), and Substring
gets everything after it — which gives you the file name with its extension.
Wrapping Up
String search methods are powerful tools in every C# developer’s toolbox. They help with checks, validations, filtering, and searching within texts — and they show up in all sorts of real-life coding situations. Knowing how to use these methods well can really boost the reliability and efficiency of your apps.