String..::.Compare Method (String, String)<!---->
<!--
Content type: Devdiv1. Transform: orcas2mtps.xslt.
-->
Updated: November 2007
Compares two specified String objects and returns an integer that indicates their relationship to one another in the sort order.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Syntax
<!---->
Visual Basic (Declaration)
|
Public Shared Function Compare ( _
strA As String, _
strB As String _
) As Integer
|
|
Dim strA As String
Dim strB As String
Dim returnValue As Integer
returnValue = String.Compare(strA, _
strB)
|
|
public static int Compare(
string strA,
string strB
)
|
|
public:
static int Compare(
String^ strA,
String^ strB
)
|
|
public static int Compare(
String strA,
String strB
)
|
|
public static function Compare(
strA : String,
strB : String
) : int
|
Return Value
Type:
System..::.Int32
A 32-bit signed integer indicating the lexical relationship between the two comparands.
<!---->
Value
Condition
Less than zero
|
strA is less than strB.
|
Zero
|
strA equals strB.
|
Greater than zero
|
strA is greater than strB.
|
Remarks
<!---->
The comparison uses the current culture 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.
One or both comparands can be nullNothingnullptra null reference (Nothing in Visual Basic). By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.
The comparison terminates when an inequality is discovered or both strings 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".
|
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}
|
|
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, True) = 0 Then
Return True
Else
Return False
End If
End Function
|
Compare the path name to "file" using an ordinal comparison. The correct code to do this is as follows:
|
static bool IsFileURI(String path)
{
return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}
|
|
Shared Function IsFileURI(ByVal path As String) As Boolean
If String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) = 0 Then
Return True
Else
Return False
End If
End Function
|
Examples
<!---->
In the following code example, the ReverseStringComparer class demonstrates how you can evaluate two strings with the Compare method.
|
Imports System
Imports System.Text
Imports System.Collections
Public Class SamplesArrayList
Public Shared Sub Main()
Dim myAL As New ArrayList()
' Creates and initializes a new ArrayList.
myAL.Add("Eric")
myAL.Add("Mark")
myAL.Add("Lance")
myAL.Add("Rob")
myAL.Add("Kris")
myAL.Add("Brad")
myAL.Add("Kit")
myAL.Add("Bradley")
myAL.Add("Keith")
myAL.Add("Susan")
' Displays the properties and values of the ArrayList.
Console.WriteLine("Count: {0}", myAL.Count)
PrintValues("Unsorted", myAL)
myAL.Sort()
PrintValues("Sorted", myAL)
Dim comp as New ReverseStringComparer
myAL.Sort(comp)
PrintValues("Reverse", myAL)
Dim names As String() = CType(myAL.ToArray(GetType(String)), String())
End Sub 'Main
Public Shared Sub PrintValues(title As String, myList As IEnumerable)
Console.Write("{0,10}: ", title)
Dim sb As New StringBuilder()
Dim s As String
For Each s In myList
sb.AppendFormat("{0}, ", s)
Next s
sb.Remove(sb.Length - 2, 2)
Console.WriteLine(sb)
End Sub 'PrintValues
End Class 'SamplesArrayList
Public Class ReverseStringComparer
Implements IComparer
Function Compare(x As Object, y As Object) As Integer implements IComparer.Compare
Dim s1 As String = CStr (x)
Dim s2 As String = CStr (y)
'negate the return value to get the reverse order
Return - [String].Compare(s1, s2)
End Function 'Compare
End Class 'ReverseStringComparer
|
|
using System;
using System.Text;
using System.Collections;
public class SamplesArrayList {
public static void Main() {
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("Eric");
myAL.Add("Mark");
myAL.Add("Lance");
myAL.Add("Rob");
myAL.Add("Kris");
myAL.Add("Brad");
myAL.Add("Kit");
myAL.Add("Bradley");
myAL.Add("Keith");
myAL.Add("Susan");
// Displays the properties and values of the ArrayList.
Console.WriteLine( "Count: {0}", myAL.Count );
PrintValues ("Unsorted", myAL );
myAL.Sort();
PrintValues("Sorted", myAL );
myAL.Sort(new ReverseStringComparer() );
PrintValues ("Reverse" , myAL );
string [] names = (string[]) myAL.ToArray (typeof(string));
}
public static void PrintValues(string title, IEnumerable myList ) {
Console.Write ("{0,10}: ", title);
StringBuilder sb = new StringBuilder();
foreach (string s in myList) {
sb.AppendFormat( "{0}, ", s);
}
sb.Remove (sb.Length-2,2);
Console.WriteLine(sb);
}
}
public class ReverseStringComparer : IComparer {
public int Compare (object x, object y) {
string s1 = x as string;
string s2 = y as string;
//negate the return value to get the reverse order
return - String.Compare (s1,s2);
}
}
|
|
using namespace System;
using namespace System::Text;
using namespace System::Collections;
ref class ReverseStringComparer: public IComparer
{
public:
virtual int Compare( Object^ x, Object^ y )
{
String^ s1 = dynamic_cast<String^>(x);
String^ s2 = dynamic_cast<String^>(y);
//negate the return value to get the reverse order
return -String::Compare( s1, s2 );
}
};
void PrintValues( String^ title, IEnumerable^ myList )
{
Console::Write( "{0,10}: ", title );
StringBuilder^ sb = gcnew StringBuilder;
{
IEnumerator^ en = myList->GetEnumerator();
String^ s;
while ( en->MoveNext() )
{
s = en->Current->ToString();
sb->AppendFormat( "{0}, ", s );
}
}
sb->Remove( sb->Length - 2, 2 );
Console::WriteLine( sb );
}
void main()
{
// Creates and initializes a new ArrayList.
ArrayList^ myAL = gcnew ArrayList;
myAL->Add( "Eric" );
myAL->Add( "Mark" );
myAL->Add( "Lance" );
myAL->Add( "Rob" );
myAL->Add( "Kris" );
myAL->Add( "Brad" );
myAL->Add( "Kit" );
myAL->Add( "Bradley" );
myAL->Add( "Keith" );
myAL->Add( "Susan" );
// Displays the properties and values of the ArrayList.
Console::WriteLine( "Count: {0}", myAL->Count.ToString() );
PrintValues( "Unsorted", myAL );
myAL->Sort();
PrintValues( "Sorted", myAL );
myAL->Sort( gcnew ReverseStringComparer );
PrintValues( "Reverse", myAL );
array<String^>^names = dynamic_cast<array<String^>^>(myAL->ToArray( String::typeid ));
}
|
|
import System.*;
import System.Text.*;
import System.Collections.*;
public class SamplesArrayList
{
public static void main(String[] args)
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("Eric");
myAL.Add("Mark");
myAL.Add("Lance");
myAL.Add("Rob");
myAL.Add("Kris");
myAL.Add("Brad");
myAL.Add("Kit");
myAL.Add("Bradley");
myAL.Add("Keith");
myAL.Add("Susan");
// Displays the properties and values of the ArrayList.
Console.WriteLine("Count: {0}", (Int32)myAL.get_Count());
PrintValues("Unsorted", myAL);
myAL.Sort();
PrintValues("Sorted", myAL);
myAL.Sort(new ReverseStringComparer());
PrintValues("Reverse", myAL);
String names[] = (String[])(myAL.ToArray(String.class.ToType()));
} //main
public static void PrintValues(String title, IEnumerable myList)
{
Console.Write("{0,10}: ", title);
StringBuilder sb = new StringBuilder();
IEnumerator objEnum = myList.GetEnumerator();
while (objEnum.MoveNext()) {
String s = System.Convert.ToString(objEnum.get_Current());
sb.AppendFormat("{0}, ", s);
}
sb.Remove(sb.get_Length() - 2, 2);
Console.WriteLine(sb);
} //PrintValues
} //SamplesArrayList
public class ReverseStringComparer implements IComparer
{
public int Compare(Object x, Object y)
{
String s1 = System.Convert.ToString(x);
String s2 = System.Convert.ToString(y);
//negate the return value to get the reverse order
return -String.Compare(s1, s2);
} //Compare
} //ReverseStringComparer
|
|
import System;
import System.Text;
import System.Collections;
public class SamplesArrayList {
public static function Main() : void {
// Creates and initializes a new ArrayList.
var myAL : ArrayList = new ArrayList();
myAL.Add("Eric");
myAL.Add("Mark");
myAL.Add("Lance");
myAL.Add("Rob");
myAL.Add("Kris");
myAL.Add("Brad");
myAL.Add("Kit");
myAL.Add("Bradley");
myAL.Add("Keith");
myAL.Add("Susan");
// Displays the properties and values of the ArrayList.
Console.WriteLine( "Count: {0}", myAL.Count );
PrintValues ("Unsorted", myAL );
myAL.Sort();
PrintValues("Sorted", myAL );
myAL.Sort(new ReverseStringComparer() );
PrintValues ("Reverse" , myAL );
var names : String [] = (String[])(myAL.ToArray (System.String));
}
public static function PrintValues(title : String, myList: IEnumerable ) : void {
Console.Write ("{0,10}: ", title);
var sb : StringBuilder = new StringBuilder();
for (var s : String in myList) {
sb.AppendFormat( "{0}, ", s);
}
sb.Remove (sb.Length-2,2);
Console.WriteLine(sb);
}
}
public class ReverseStringComparer implements IComparer {
public function Compare (x, y) : int {
//negate the return value to get the reverse order
return - String.Compare (String(x), String(y));
}
}
SamplesArrayList.Main(); |
分享到:
相关推荐
Contents Contents ii List of Tables x List of Figures xiv 1 Scope 1 2 Normative references 2 3 Terms and definitions 3 4 General principles 7 4.1 Implementation compliance . ....4.2 Structure of this ...
if (String.Compare(strHttpMethod, METHOD_POST, true) == 0) 17. { // POSTのI場e合? bufBody = encAsc.GetBytes(strParam); 18. httpReq.ContentLength = bufBody.Length; 19. stmReq = httpReq....
Contents Contents iii List of Tables xi List of Figures xv 1 General 1 1.1 Scope . . . . ....1.2 Normative references ....1.3 Terms and definitions ....1.4 Implementation compliance ....1.5 Structure of this ...
StringTrim 14.2.12. StripTags 14.3. 过滤器链 14.4. 编写过滤器 14.5. Zend_Filter_Input 14.5.1. Declaring Filter and Validator Rules 14.5.2. Creating the Filter and Validator Processor 14.5.3. ...
cmd.CommandText = string.Format( "INSERT INTO INDIVIDUAL (ID, FIRSTNAME, MIDDLENAME, LASTNAME, DOB, STATE) VALUES({0}, '{1}', '{2}', '{3}', '{4}', '{5}');", id, firstname, middlename, ...
A favorite method among power users is the Quick Open in the File menu. The benefit of the quick open dialog is that it loads up very... Vertical & Horizontal Split Window This is a convenient ...
String Keys are UTF8 encoded and limited to 60 bytes if not specified otherwise (maximum is 255 chars). Support for long string Keys with the RaptorDBString class. Duplicate keys are stored as a WAH ...
关于雷达方面的知识! EFFECTIVENESS OF EXTRACTING WATER SURFACE SLOPES FROM LIDAR DATA WITHIN THE ACTIVE CHANNEL: SANDY RIVER, OREGON, USA by JOHN THOMAS ENGLISH A THESIS Presented to the Department ...
useString.java 使用String示例 YanghuiTri.java 构造和显示杨辉三角 第6章 示例描述:本章学习Java的异常处理。 demoException_1.java 异常示例1 demoException_2.java 异常示例2 demoException_3.java 异常...
-layers method optimize, merge, or compare image layers -level value adjust the level of image contrast -level-colors color,color level image with the given colors -linear-stretch geometry ...
// TODO Auto-generated method stub new DengLu().DengLu(); //new ZhuCe(); } //设置键盘监听的处理 public class Key extends KeyAdapter{ public void keyPressed(KeyEvent e) { int code = e....
long string. PAQ6 uses predictive arithmetic coding. The string, y, is compressed by representing it as a base 256 number, x, such that: P(s ) (s ) (1) where s is chosen randomly from the ...
“数字感知”字符串比较算法的定义和实现:'A1' < 'A2' < 'A3' < 'A10' < 'A11' < 'B1'。
%I - current request thread name (can compare later with stacktraces) There is also support to write information from the cookie, incoming header, outgoing response headers, the Session or something...
#Note 项目已退役,不在积极开发中。 jquery.filterOptions 一个 jQuery 插件,用于过滤选择元素内的选项。... * @param {String} str - String to compare * @param {Boolean} isCaseSensitive - is case sensi
xvii Contents Finishing Your Modules 154 Defining Module-Specific Errors 154 Choosing What to Export 155 Documenting Your Modules 156 Try It Out: Viewing Module Documentation ...
fixed string table (part of lowlevel string processing of NativeXml) * integrated End-Of-Line normalisation in the XML parser * placed NativeXmlC14N.pas in NativeXml.pas, TNativeXml.Canonicalize ...
变量句柄2 JVM 原子操作的安全而有效的... # {method} {0x00007f79679e1f40} 'compareAndSetWithUnsafe' '(Ljava/lang/String;Ljava/lang/String;)Z' in 'test/VarHandle2PerfTest' # this: rsi:rsi = 'test/VarHa
private static final String TAG = "ViewPager"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int DEFAULT_OFFSCREEN_PAGES = 1; ...
CMPS/CMPSB/CMPSW/CMPSD Compare String Operands CWD/CDQ Convert Word to Doubleword/Convert Doubleword to DAA Decimal Adjust AL after Addition DAS Decimal Adjust AL after Subtraction DEC Decrement by 1 ...