#97 – String Comparisons Using Other Cultures

Each language has different rules for how to sort strings, based on the alphabetical ordering of the characters used for that language.  In .NET, information about a language/place combination is captured in an instance of the CultureInfo class.  In turn, the CultureInfo object has a CompareInfo property that points to an instance of the CompareInfo class, defining rules for sorting strings in that culture.

By default, when you use the String.Compare method, the sorting rules for the current culture (CultureInfo.CurrentCulture) are used.  But you can override this by adding a CultureInfo parameter on the Compare method.

You can pass a new instance of CultureInfo by creating an instance using a unique culture code.  The culture code indicates language and region.

 int n;
 n = string.Compare("åb", "bb", true);  // -1 (å < b in English)
 n = string.Compare("åb", "bb", true, new CultureInfo("nn-NO"));    // 1  (å > b in Norwegian)
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: