C # string processing. NET provides the string class and the system. Text namespace to quickly implement the string processing function.
String comparison strings refer to the dictionary-based sorting rules to determine the size of the two strings. The front letter must be smaller than the back letter. In the string class, common methods for comparing strings include compare, compareto, compareordinal, and equals. The compare method compare is a static method of the string class. It is used to compare two string objects. There are multiple overload methods:
Int Compare(string strA, string strB)Int Compare(string strA, string strB, bool ignoreCase)Int Compare(string strA, string strB, bool ignoreCase, CultureInfo)Int Compare(string strA, int indexA, string strB, int indexB, int length)Int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
The meanings of parameters are as follows:
- Stra, strb -- two strings to be compared;
- Ignorecase -- specifies whether case sensitivity is taken into account. If the value is true, Case sensitivity is ignored;
- Indexa, indexb -- when we need to compare the substrings of two strings, Indexa and indexb are the starting positions of the substrings respectively;
- Length -- maximum length of the string to be compared;
- Culture -- The Regional Information of the string.
The Return Value of the compare method: If stra> strb, a positive integer is returned. If stra = strb, 0 is returned. If stra <strb, a negative integer is returned.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; namespace consoleapplication1 {class program {static void main (string [] ARGs) {string stra = ""; string strb = ""; // string comparison console. writeline (string. compare (stra, strb); console. writeline (string. compare (stra, stra); console. writeline (string. compare (strb, stra ));}}}
Output:
Note: The compareordinal and compare methods are very similar, but the regional issues are not considered. The compareordinal method will not be described in detail below. The compareto method compares the current String object with another string object. The function is similar to the compare method, and the return value is the same. The difference between the compareto and compare methods is:
- The compareto method is not a static method and can be called through a String object;
- The compareto method is not overloaded and can only compare two strings in case sensitive mode.
The following uses compareto to compare two strings:
String stra = ""; string strb = ""; console. writeline (stra. compareto (strb ));
The equals method returns true if the two strings are equal. Otherwise, false is returned.
String stra = ""; string strb = ""; console. writeline (string. Equals (stra, strb); console. writeline (stra. Equals (strb ));
Locate characters and substrings
C # string processing