How to compare two strings c

How to compare two strings c

How to compare strings in C#

You compare strings to answer one of two questions: «Are these two strings equal?» or «In what order should these strings be placed when sorting them?»

Those two questions are complicated by factors that affect string comparisons:

The C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

When you compare strings, you define an order among them. Comparisons are used to sort a sequence of strings. Once the sequence is in a known order, it is easier to search, both for software and for humans. Other comparisons may check if strings are the same. These sameness checks are similar to equality, but some differences, such as case differences, may be ignored.

Default ordinal comparisons

By default, the most common operations:

perform a case-sensitive, ordinal comparison. In the case of String.Equals, a StringComparison argument can be provided to alter its sorting rules. The following example demonstrates that:

The default ordinal comparison doesn’t take linguistic rules into account when comparing strings. It compares the binary value of each Char object in two strings. As a result, the default ordinal comparison is also case-sensitive.

Case-insensitive ordinal comparisons

The String.Equals(String, StringComparison) method enables you to specify a StringComparison value of StringComparison.OrdinalIgnoreCase for a case-insensitive ordinal comparison. There is also a static String.Compare(String, String, StringComparison) method that performs a case-insensitive ordinal comparison if you specify a value of StringComparison.OrdinalIgnoreCase for the StringComparison argument. These are shown in the following code:

When performing a case-insensitive ordinal comparison, these methods use the casing conventions of the invariant culture.

Linguistic comparisons

Strings can also be ordered using linguistic rules for the current culture. This is sometimes referred to as «word sort order.» When you perform a linguistic comparison, some nonalphanumeric Unicode characters might have special weights assigned. For example, the hyphen «-» may have a small weight assigned to it so that «co-op» and «coop» appear next to each other in sort order. In addition, some Unicode characters may be equivalent to a sequence of Char instances. The following example uses the phrase «They dance in the street.» in German with the «ss» (U+0073 U+0073) in one string and ‘Гџ’ (U+00DF) in another. Linguistically (in Windows), «ss» is equal to the German Esszet: ‘Гџ’ character in both the «en-US» and «de-DE» cultures.

Comparisons using specific cultures

This sample stores CultureInfo objects for the en-US and de-DE cultures. The comparisons are performed using a CultureInfo object to ensure a culture-specific comparison.

The culture used affects linguistic comparisons. The following example shows the results of comparing the two German sentences using the «en-US» culture and the «de-DE» culture:

Culture-sensitive comparisons are typically used to compare and sort strings input by users with other strings input by users. The characters and sorting conventions of these strings might vary depending on the locale of the user’s computer. Even strings that contain identical characters might sort differently depending on the culture of the current thread.

Linguistic sorting and searching strings in arrays

The following examples show how to sort and search for strings in an array using a linguistic comparison dependent on the current culture. You use the static Array methods that take a System.StringComparer parameter.

This example shows how to sort an array of strings using the current culture:

Once the array is sorted, you can search for entries using a binary search. A binary search starts in the middle of the collection to determine which half of the collection would contain the sought string. Each subsequent comparison subdivides the remaining part of the collection in half. The array is sorted using the StringComparer.CurrentCulture. The local function ShowWhere displays information about where the string was found. If the string wasn’t found, the returned value indicates where it would be if it were found.

Ordinal sorting and searching in collections

Once sorted, the list of strings can be searched using a binary search. The following sample shows how to search the sorted list using the same comparison function. The local function ShowWhere shows where the sought text is or would be:

Always make sure to use the same type of comparison for sorting and searching. Using different comparison types for sorting and searching produces unexpected results.

.NET provides several methods to compare the values of strings. The following table lists and describes the value-comparison methods.

Method nameUse
String.CompareCompares the values of two strings. Returns an integer value.
String.CompareOrdinalCompares two strings without regard to local culture. Returns an integer value.
String.CompareToCompares the current string object to another string. Returns an integer value.
String.StartsWithDetermines whether a string begins with the string passed. Returns a Boolean value.
String.EndsWithDetermines whether a string ends with the string passed. Returns a Boolean value.
String.ContainsDetermines whether a character or string occurs within another string. Returns a Boolean value.
String.EqualsDetermines whether two strings are the same. Returns a Boolean value.
String.IndexOfReturns the index position of a character or string, starting from the beginning of the string you are examining. Returns an integer value.
String.LastIndexOfReturns the index position of a character or string, starting from the end of the string you are examining. Returns an integer value.

Compare method

The static String.Compare method provides a thorough way of comparing two strings. This method is culturally aware. You can use this function to compare two strings or substrings of two strings. Additionally, overloads are provided that regard or disregard case and cultural variance. The following table shows the three integer values that this method might return.

Return valueCondition
A negative integerThe first string precedes the second string in the sort order.

1

The first string follows the second string in the sort order.

The String.Compare method is primarily intended for use when ordering or sorting strings. You should not use the String.Compare method to test for equality (that is, to explicitly look for a return value of 0 with no regard for whether one string is less than or greater than the other). Instead, to determine whether two strings are equal, use the String.Equals(String, String, StringComparison) method.

The following example uses the String.Compare method to determine the relative values of two strings.

The preceding example is culture-sensitive by default. To perform a culture-insensitive string comparison, use an overload of the String.Compare method that allows you to specify the culture to use by supplying a culture parameter. For an example that demonstrates how to use the String.Compare method to perform a culture-insensitive comparison, see Culture-insensitive string comparisons.

CompareOrdinal method

The String.CompareOrdinal method compares two string objects without considering the local culture. The return values of this method are identical to the values returned by the Compare method in the previous table.

The String.CompareOrdinal method is primarily intended for use when ordering or sorting strings. You should not use the String.CompareOrdinal method to test for equality (that is, to explicitly look for a return value of 0 with no regard for whether one string is less than or greater than the other). Instead, to determine whether two strings are equal, use the String.Equals(String, String, StringComparison) method.

The following example uses the CompareOrdinal method to compare the values of two strings.

CompareTo method

The String.CompareTo method compares the string that the current string object encapsulates to another string or object. The return values of this method are identical to the values returned by the String.Compare method in the previous table.

The String.CompareTo method is primarily intended for use when ordering or sorting strings. You should not use the String.CompareTo method to test for equality (that is, to explicitly look for a return value of 0 with no regard for whether one string is less than or greater than the other). Instead, to determine whether two strings are equal, use the String.Equals(String, String, StringComparison) method.

The following example uses the String.CompareTo method to compare the string1 object to the string2 object.

All overloads of the String.CompareTo method perform culture-sensitive and case-sensitive comparisons by default. No overloads of this method are provided that allow you to perform a culture-insensitive comparison. For code clarity, we recommend that you use the String.Compare method instead, specifying CultureInfo.CurrentCulture for culture-sensitive operations or CultureInfo.InvariantCulture for culture-insensitive operations. For examples that demonstrate how to use the String.Compare method to perform both culture-sensitive and culture-insensitive comparisons, see Performing Culture-Insensitive String Comparisons.

Equals method

The String.Equals method can easily determine if two strings are the same. This case-sensitive method returns a true or false Boolean value. It can be used from an existing class, as illustrated in the next example. The following example uses the Equals method to determine whether a string object contains the phrase «Hello World».

This example displays True to the console.

This method can also be used as a static method. The following example compares two string objects using a static method.

This example displays True to the console.

StartsWith and EndsWith methods

You can use the String.StartsWith method to determine whether a string object begins with the same characters that encompass another string. This case-sensitive method returns true if the current string object begins with the passed string and false if it does not. The following example uses this method to determine if a string object begins with «Hello».

This example displays True to the console.

The String.EndsWith method compares a passed string to the characters that exist at the end of the current string object. It also returns a Boolean value. The following example checks the end of a string using the EndsWith method.

This example displays False to the console.

IndexOf and LastIndexOf methods

You can use the String.IndexOf method to determine the position of the first occurrence of a particular character within a string. This case-sensitive method starts counting from the beginning of a string and returns the position of a passed character using a zero-based index. If the character cannot be found, a value of –1 is returned.

The following example uses the IndexOf method to search for the first occurrence of the ‘ l ‘ character in a string.

This example displays 2 to the console.

The String.LastIndexOf method is similar to the String.IndexOf method except that it returns the position of the last occurrence of a particular character within a string. It is case-sensitive and uses a zero-based index.

The following example uses the LastIndexOf method to search for the last occurrence of the ‘ l ‘ character in a string.

Comparing two strings in C? [duplicate]

This code is not working as the comparison is not being done. Why?

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you (wrongly) use

you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

For comparing 2 strings, either use the built in function strcmp() using header file string.h

OR you can write your own function like this:

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

You are currently comparing the addresses of the two strings.

Use strcmp to compare the values of two char arrays

You try and compare pointers here, not the contents of what is pointed to (ie, your characters).

You must use either memcmp or str<,n>cmp to compare the contents.

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

How to compare two strings c. Смотреть фото How to compare two strings c. Смотреть картинку How to compare two strings c. Картинка про How to compare two strings c. Фото How to compare two strings c

You need to use strcmp :

To answer the WHY in your question:

Because the equality operator can only be applied to simple variable types, such as float s, int s, or char s, and not to more sophisticated types, such as structures or arrays. To determine if two strings are equal, you must explicitly compare the two character strings character by character.

String. Compare Method

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

Overloads

Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

Remarks

All overloads of the Compare method return a 32-bit signed integer indicating the lexical relationship between the two comparands.

ValueCondition
Less than zeroThe first substring precedes the second substring in the sort order.
ZeroThe substrings occur in the same position in the sort order, or length is zero.
Greater than zeroThe first substring follows the second substring in the sort order.

Whenever possible, you should call an overload of the Compare method that includes a StringComparison parameter. For more information, see Best Practices for Using Strings.

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)

Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

Parameters

The first string to use in the comparison.

The second string to use in the comparison.

The maximum number of characters in the substrings to compare.

Options to use when performing the comparison (such as ignoring case or symbols).

Returns

An integer that indicates the lexical relationship between the two substrings, as shown in the following table.

ValueCondition
Less than zeroThe substring in strA precedes the substring in strB in the sort order.
ZeroThe substrings occur in the same position in the sort order, or length is zero.
Greater than zeroThe substring in strA follows the substring in strB in the sort order.

Exceptions

options is not a CompareOptions value.

Examples

The following example uses the Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method to compare the last names of two people. It then lists them in alphabetical order.

Remarks

The comparison uses the culture parameter to obtain culture-specific information, such as casing rules and the alphabetical order of individual characters. For example, a particular culture could specify that certain combinations of characters be treated as a single character, that uppercase and lowercase characters be compared in a particular way, or that the sort order of a character depends on the characters that precede or follow it.

The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method is designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two substrings are equivalent (that is, when the purpose of the method call is to test for a return value of zero). To determine whether two strings are equivalent, call the Equals method.

The comparison can be further specified by the options parameter, which consists of one or more members of the System.Globalization.CompareOptions enumeration. However, because the purpose of this method is to conduct a culture-sensitive string comparison, the CompareOptions.Ordinal and CompareOptions.OrdinalIgnoreCase values have no effect.

The comparison terminates when an inequality is discovered or both substrings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with the remaining characters is considered greater. The return value is the result of the last comparison performed.

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

See also

Applies to

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

Parameters

The first string to use in the comparison.

The second string to use in the comparison.

The maximum number of characters in the substrings to compare.

Returns

An integer that indicates the lexical relationship between the two comparands.

ValueCondition
Less than zeroThe substring in strA precedes the substring in strB in the sort order.
ZeroThe substrings occur in the same position in the sort order, or length is zero.
Greater than zeroThe substring in strA follows the substring in strB in the sort order.

Exceptions

Examples

The following example compares two substrings using different cultures and ignoring the case of the substrings. The choice of culture affects how the letter «I» is compared.

Remarks

The comparison uses the culture parameter to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

The comparison is performed using word sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions.

The comparison terminates when an inequality is discovered or both substrings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, then the string with remaining characters is considered greater. The return value is the result of the last comparison performed.

Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter «i» in «file».

Compare the path name to «file» using an ordinal comparison. The correct code to do this is as follows:

Notes to Callers

Character sets include ignorable characters. The Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) method does not consider these characters when it performs a linguistic or culture-sensitive comparison. To recognize ignorable characters in your comparison, call the Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method and supply a value of Ordinal or OrdinalIgnoreCase for the options parameter.

.NET provides extensive support for developing localized and globalized applications, and makes it easy to apply the conventions of either the current culture or a specific culture when performing common operations such as sorting and displaying strings. But sorting or comparing strings is not always a culture-sensitive operation. For example, strings that are used internally by an application typically should be handled identically across all cultures. When culturally independent string data, such as XML tags, HTML tags, user names, file paths, and the names of system objects, are interpreted as if they were culture-sensitive, application code can be subject to subtle bugs, poor performance, and, in some cases, security issues.

Recommendations for string usage

Avoid the following practices when you compare strings:

Specifying string comparisons explicitly

StringComparison memberDescription
CurrentCulturePerforms a case-sensitive comparison using the current culture.
CurrentCultureIgnoreCasePerforms a case-insensitive comparison using the current culture.
InvariantCulturePerforms a case-sensitive comparison using the invariant culture.
InvariantCultureIgnoreCasePerforms a case-insensitive comparison using the invariant culture.
OrdinalPerforms an ordinal comparison.
OrdinalIgnoreCasePerforms a case-insensitive ordinal comparison.

For example, the IndexOf method, which returns the index of a substring in a String object that matches either a character or a string, has nine overloads:

We recommend that you select an overload that does not use default values, for the following reasons:

Some overloads with default parameters (those that search for a Char in the string instance) perform an ordinal comparison, whereas others (those that search for a string in the string instance) are culture-sensitive. It is difficult to remember which method uses which default value, and easy to confuse the overloads.

In general, we recommend that you call a method that does not rely on defaults, because it makes the intent of the code unambiguous. This, in turn, makes the code more readable and easier to debug and maintain. The following example addresses the questions raised about the previous example. It makes it clear that ordinal comparison is used and that differences in case are ignored.

The details of string comparison

String comparison is the heart of many string-related operations, particularly sorting and testing for equality. Strings sort in a determined order: If «my» appears before «string» in a sorted list of strings, «my» must compare less than or equal to «string». Additionally, comparison implicitly defines equality. The comparison operation returns zero for strings it deems equal. A good interpretation is that neither string is less than the other. Most meaningful operations involving strings include one or both of these procedures: comparing with another string, and executing a well-defined sort operation.

You can download the Sorting Weight Tables, a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, and the Default Unicode Collation Element Table, the latest version of the sort weight table for Linux and macOS. The specific version of the sort weight table on Linux and macOS depends on the version of the International Components for Unicode libraries installed on the system. For information on ICU versions and the Unicode versions that they implement, see Downloading ICU.

However, evaluating two strings for equality or sort order does not yield a single, correct result; the outcome depends on the criteria used to compare the strings. In particular, string comparisons that are ordinal or that are based on the casing and sorting conventions of the current culture or the invariant culture (a locale-agnostic culture based on the English language) may produce different results.

String comparisons that use the current culture

One criterion involves using the conventions of the current culture when comparing strings. Comparisons that are based on the current culture use the thread’s current culture or locale. If the culture is not set by the user, it defaults to the setting in the Regional Options window in Control Panel. You should always use comparisons that are based on the current culture when data is linguistically relevant, and when it reflects culture-sensitive user interaction.

Case-insensitive comparisons that use the current culture are the same as culture-sensitive comparisons, except that they ignore case as dictated by the thread’s current culture. This behavior may manifest itself in sort orders as well.

Comparisons that use current culture semantics are the default for the following methods:

In any case, we recommend that you call an overload that has a StringComparison parameter to make the intent of the method call clear.

Subtle and not so subtle bugs can emerge when non-linguistic string data is interpreted linguistically, or when string data from a particular culture is interpreted using the conventions of another culture. The canonical example is the Turkish-I problem.

For nearly all Latin alphabets, including U.S. English, the character «i» (\u0069) is the lowercase version of the character «I» (\u0049). This casing rule quickly becomes the default for someone programming in such a culture. However, the Turkish («tr-TR») alphabet includes an «I with a dot» character «Д°» (\u0130), which is the capital version of «i». Turkish also includes a lowercase «i without a dot» character, «Д±» (\u0131), which capitalizes to «I». This behavior occurs in the Azerbaijani («az») culture as well.

Therefore, assumptions made about capitalizing «i» or lowercasing «I» are not valid among all cultures. If you use the default overloads for string comparison routines, they will be subject to variance between cultures. If the data to be compared is non-linguistic, using the default overloads can produce undesirable results, as the following attempt to perform a case-insensitive comparison of the strings «file» and «FILE» illustrates.

This comparison could cause significant problems if the culture is inadvertently used in security-sensitive settings, as in the following example. A method call such as IsFileURI(«file:») returns true if the current culture is U.S. English, but false if the current culture is Turkish. Thus, on Turkish systems, someone could circumvent security measures that block access to case-insensitive URIs that begin with «FILE:».

In this case, because «file:» is meant to be interpreted as a non-linguistic, culture-insensitive identifier, the code should instead be written as shown in the following example:

Ordinal string operations

Specifying the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase value in a method call signifies a non-linguistic comparison in which the features of natural languages are ignored. Methods that are invoked with these StringComparison values base string operation decisions on simple byte comparisons instead of casing or equivalence tables that are parameterized by culture. In most cases, this approach best fits the intended interpretation of strings while making code faster and more reliable.

Ordinal comparisons are string comparisons in which each byte of each string is compared without linguistic interpretation; for example, «windows» does not match «Windows». This is essentially a call to the C runtime strcmp function. Use this comparison when the context dictates that strings should be matched exactly or demands conservative matching policy. Additionally, ordinal comparison is the fastest comparison operation because it applies no linguistic rules when determining a result.

Although string comparison methods disregard embedded null characters, string search methods such as String.Contains, String.EndsWith, String.IndexOf, String.LastIndexOf, and String.StartsWith do not.

The following example performs a culture-sensitive comparison of the string «Aa» with a similar string that contains several embedded null characters between «A» and «a», and shows how the two strings are considered equal:

However, the strings are not considered equal when you use ordinal comparison, as the following example shows:

Case-insensitive ordinal comparisons are the next most conservative approach. These comparisons ignore most casing; for example, «windows» matches «Windows». When dealing with ASCII characters, this policy is equivalent to StringComparison.Ordinal, except that it ignores the usual ASCII casing. Therefore, any character in [A, Z] (\u0041-\u005A) matches the corresponding character in [a,z] (\u0061-\007A). Casing outside the ASCII range uses the invariant culture’s tables. Therefore, the following comparison:

is equivalent to (but faster than) this comparison:

These comparisons are still very fast.

Both StringComparison.Ordinal and StringComparison.OrdinalIgnoreCase use the binary values directly, and are best suited for matching. When you are not sure about your comparison settings, use one of these two values. However, because they perform a byte-by-byte comparison, they do not sort by a linguistic sort order (like an English dictionary) but by a binary sort order. The results may look odd in most contexts if displayed to users.

Ordinal semantics are the default for String.Equals overloads that do not include a StringComparison argument (including the equality operator). In any case, we recommend that you call an overload that has a StringComparison parameter.

String operations that use the invariant culture

Comparisons with the invariant culture use the CompareInfo property returned by the static CultureInfo.InvariantCulture property. This behavior is the same on all systems; it translates any characters outside its range into what it believes are equivalent invariant characters. This policy can be useful for maintaining one set of string behavior across cultures, but it often provides unexpected results.

Case-insensitive comparisons with the invariant culture use the static CompareInfo property returned by the static CultureInfo.InvariantCulture property for comparison information as well. Any case differences among these translated characters are ignored.

Comparisons that use StringComparison.InvariantCulture and StringComparison.Ordinal work identically on ASCII strings. However, StringComparison.InvariantCulture makes linguistic decisions that might not be appropriate for strings that have to be interpreted as a set of bytes. The CultureInfo.InvariantCulture.CompareInfo object makes the Compare method interpret certain sets of characters as equivalent. For example, the following equivalence is valid under the invariant culture:

InvariantCulture: a + МЉ = ГҐ

The LATIN SMALL LETTER A character «a» (\u0061), when it is next to the COMBINING RING ABOVE character «+ » МЉ» (\u030a), is interpreted as the LATIN SMALL LETTER A WITH RING ABOVE character «ГҐ» (\u00e5). As the following example shows, this behavior differs from ordinal comparison.

When interpreting file names, cookies, or anything else where a combination such as «ГҐ» can appear, ordinal comparisons still offer the most transparent and fitting behavior.

On balance, the invariant culture has very few properties that make it useful for comparison. It does comparison in a linguistically relevant manner, which prevents it from guaranteeing full symbolic equivalence, but it is not the choice for display in any culture. One of the few reasons to use StringComparison.InvariantCulture for comparison is to persist ordered data for a cross-culturally identical display. For example, if a large data file that contains a list of sorted identifiers for display accompanies an application, adding to this list would require an insertion with invariant-style sorting.

Choosing a StringComparison member for your method call

The following table outlines the mapping from semantic string context to a StringComparison enumeration member:

DataBehaviorCorresponding System.StringComparison

value

Case-sensitive internal identifiers.

Case-sensitive identifiers in standards such as XML and HTTP.

Case-sensitive security-related settings.

A non-linguistic identifier, where bytes match exactly.Ordinal
Case-insensitive internal identifiers.

Case-insensitive identifiers in standards such as XML and HTTP.

Registry keys and values.

Resource identifiers (for example, handle names).

Case-insensitive security-related settings.

A non-linguistic identifier, where case is irrelevant; especially data stored in most Windows system services.OrdinalIgnoreCase
Some persisted, linguistically relevant data.

Display of linguistic data that requires a fixed sort order.

Culturally agnostic data that still is linguistically relevant.InvariantCulture

InvariantCultureIgnoreCase

Data displayed to the user.

Most user input.

Data that requires local linguistic customs.CurrentCulture

The following sections describe the methods that are most commonly used for string comparison.

String.Compare

As the operation most central to string interpretation, all instances of these method calls should be examined to determine whether strings should be interpreted according to the current culture, or dissociated from the culture (symbolically). Typically, it is the latter, and a StringComparison.Ordinal comparison should be used instead.

The System.Globalization.CompareInfo class, which is returned by the CultureInfo.CompareInfo property, also includes a Compare method that provides a large number of matching options (ordinal, ignoring white space, ignoring kana type, and so on) by means of the CompareOptions flag enumeration.

String.CompareTo

This method does not currently offer an overload that specifies a StringComparison type. It is usually possible to convert this method to the recommended String.Compare(String, String, StringComparison) form.

Types that implement the IComparable and IComparable interfaces implement this method. Because it does not offer the option of a StringComparison parameter, implementing types often let the user specify a StringComparer in their constructor. The following example defines a FileName class whose class constructor includes a StringComparer parameter. This StringComparer object is then used in the FileName.CompareTo method.

String.Equals

The String class lets you test for equality by calling either the static or instance Equals method overloads, or by using the static equality operator. The overloads and operator use ordinal comparison by default. However, we still recommend that you call an overload that explicitly specifies the StringComparison type even if you want to perform an ordinal comparison; this makes it easier to search code for a certain string interpretation.

String.ToUpper and String.ToLower

Be careful when you use the String.ToUpper() and String.ToLower() methods, because forcing a string to a uppercase or lowercase is often used as a small normalization for comparing strings regardless of case. If so, consider using a case-insensitive comparison.

The String.ToUpperInvariant and String.ToLowerInvariant methods are also available. ToUpperInvariant is the standard way to normalize case. Comparisons made using StringComparison.OrdinalIgnoreCase are behaviorally the composition of two calls: calling ToUpperInvariant on both string arguments, and doing a comparison using StringComparison.Ordinal.

Overloads are also available for converting to uppercase and lowercase in a specific culture, by passing a CultureInfo object that represents that culture to the method.

Char.ToUpper and Char.ToLower

The Char.ToUpper(Char) and Char.ToLower(Char) methods work similarly to the String.ToUpper() and String.ToLower() methods described in the previous section.

String.StartsWith and String.EndsWith

By default, both of these methods perform a culture-sensitive comparison.

String.IndexOf and String.LastIndexOf

There is a lack of consistency in how the default overloads of these methods perform comparisons. All String.IndexOf and String.LastIndexOf methods that include a Char parameter perform an ordinal comparison, but the default String.IndexOf and String.LastIndexOf methods that include a String parameter perform a culture-sensitive comparison.

If you call the String.IndexOf(String) or String.LastIndexOf(String) method and pass it a string to locate in the current instance, we recommend that you call an overload that explicitly specifies the StringComparison type. The overloads that include a Char argument do not allow you to specify a StringComparison type.

Methods that perform string comparison indirectly

Some non-string methods that have string comparison as a central operation use the StringComparer type. The StringComparer class includes six static properties that return StringComparer instances whose StringComparer.Compare methods perform the following types of string comparisons:

Array.Sort and Array.BinarySearch

A recommended variation appears in the following example, which uses the same ordinal (culture-insensitive) comparison method both to sort and to search the array. The change code is reflected in the lines labeled Line A and Line B in the two examples.

If this data is persisted and moved across cultures, and sorting is used to present this data to the user, you might consider using StringComparison.InvariantCulture, which operates linguistically for better user output but is unaffected by changes in culture. The following example modifies the two previous examples to use the invariant culture for sorting and searching the array.

Collections example: Hashtable constructor

Hashing strings provides a second example of an operation that is affected by the way in which strings are compared.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *