Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

2.8. Comparing a String to the Beginning or End of a Second String

Problem

You need to determine whether a string is at the head or tail of a second string. In addition, the case sensitivity of the search needs to be controlled.

Solution

Use the EndsWith or StartsWith instance methods on a string object. Comparisons with EndsWith and StartsWith are always case-sensitive. The following code compares the value in the string variable head to the beginning of the string Test:

string head = "str";
string test = "strVarName";
bool isFound = test.StartsWith(head);

The following example compares the value in the string variable Tail to the end of the string test:

string tail = "Name";
string test = "strVarName";
bool isFound = test.EndsWith(tail);

In both examples, the isFound Boolean variable is set to true, since each string is found in test.

To do a case-insensitive comparison, employ the static string.Compare method. The following two examples modify the previous two examples by performing a case-insensitive comparison. The first is equivalent to a case-insensitive StartsWith string search:

string head = "str";
string test = "strVarName";
int isFound = string.Compare(head, 0, test, 0, head.Length, true);

The second is equivalent to a case-insensitive EndsWith string search:

string tail = "Name";
string test = "strVarName";
int isFound = string.Compare(tail, 0, test, (test.Length - tail.Length), 
                             tail.Length, true);

Discussion

Use the BeginsWith or EndsWith instance methods to do a case-sensitive ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata