Tips for working with strings in C# 2.0

by Mads Kristensen 28. April 2006 01:33

Working with strings is something all developers do all the time. It’s probably the thing we spend more time with above anything else. In C# 2.0 many new features for string manipulation has been added, so I’ll dig into some of those.

String.ToLowerInvariant/String.ToUpperInvariant

These are two new ways of turning a string into pure lowercased or uppercased characters, but add an invariant culture as IFormatProvider. If you are used to ToLower and ToUpper then you should use the new ones.

string foo = "hello";
foo = foo.ToUpperInvariant();

When comparing two strings in a case-insensitive way, you should uppercase them instead of lowercase. The ToUpperInvariant method performs better than ToLowerInvariant.

string foo1 = "hello";
string foo2 = "HeLLo";
if (foo1.ToUpperInvariant() == foo2.ToUpperInvariant())
{
   DoSomething();
}

Read more about ToLowerInvariant and ToUpperInvariant on MSDN.

String.Contains

Visual Basic has had this method for many years, but it was called InStr.

string foo = "hello";
bool test = foo.Contains("he");

If the string "he" is contained within foo, then it return true. It is case-sensitive, so you should uppercase both string if you want a case-insensitive comparison.

string foo = "HeLLo";
bool test = foo.ToUpperInvariant().Contains("he".ToUpperInvariant());

Read more about the Contains method on MSDN

String.Equals

This method compares two strings and returns true if they are the same. It is overloaded and lets you decide if you want a case-sensitive or case-insensitive comparison.

Here is a case-sensitive comparision:
string foo = "hello";
bool test = foo.Equals("hello");

And here it is in a case-insensitive version:
string foo = "hello";
bool test = foo.Equals("hello", StringComparison.OrdinalIgnoreCase);

Read more about the Equals method on MSDN

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

Server-side

Comments

10/8/2007 9:12:45 AM #

john

Thanks learning new thing every day == programming Smile

john United States |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008