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(); |
分享到:
相关推荐
10. **string**:`String` 类型用于表示不可变的字符序列,是Java中最常用的类之一。 11. **double**:`double` 是一种数据类型,用于存储双精度浮点数。 12. **int**:`int` 代表整型数据,用于存储整数值。 13....
10. **string**:`String`是Java中的一个类,用于处理字符串数据。 11. **double**:`double`是Java的基本数据类型之一,表示双精度浮点数。 12. **int**:`int`代表整数类型,用于存储整数值。 13. **char**:`...
48. **Compare**:比较操作用于检查两个值是否相等或具有某种关系。 49. **Temp**:临时变量用于存储中间计算结果。 50. **Null**:在Python中,None代表空或无值。 51. **Exception/Error**:异常是程序运行时...
String nextFloat = String.valueOf(new Random().nextFloat()).substring(1, 4); 正确的写法:Random random = new Random(); int proportion = random.nextInt(100) + 1; String nextFloat = String.valueOf...
- **Objective:** Swap the first and last characters of a given string. - **Key Concepts:** - Slicing strings. - Concatenating strings. 10. **Summing Anything** - **Objective:** Create a function...
例如,通过`Class.forName()`加载类,`newInstance()`创建对象,`Method.invoke()`调用方法。 2. 集合框架:Java集合框架包括接口和实现类,如List(ArrayList、LinkedList)、Set(HashSet、TreeSet)和Map...
=, <, >, , >=) are used to compare values. **Controlling the Flow of Execution** Control structures such as conditionals (if-else statements) and loops (while and for loops) are essential for ...
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 ...
例如:`$('#ID').sort({order:'desc',method:'advance',type:'string',sortItem:'name',sortAttr:'class'})`。这些参数选项包括: 1. `order`:定义排序顺序,可以设置为`'asc'`(升序)或`'desc'`(降序)。 2. `...
Comparator<String> comp = (s1, s2) -> Integer.compare(s1.length(), s2.length()); ``` 3. **方法参考 - 静态方法** 直接引用`Integer::compare`静态方法: ```java Comparator<String> comp = ...
Optional<Integer> max = numbers.stream().max(Integer::compare); max.ifPresent(System.out::println); // 输出:5 ``` #### 五、总结 Java 8通过引入Lambda表达式和Stream API,极大地丰富了Java的编程模型...
return Integer.compare(this.actionValue, other.actionValue); } } ``` #### 五、包(Package) **定义:** 包是 Java 中用于组织类和接口的一种方式。 **例子:** - `java.lang`: 提供核心类,如 `String`, ...
public GoodStudent(String name, int age, String gender) { super(name, age, gender); } @Override public void hardWork() { System.out.println(name + " is working hard."); } } class BadStudent ...
public int compare(Integer o1, Integer o2) { return o1 - o2; } }); System.out.println(list); // [-15, 5, 10, 20, 25] // JDK 1.8 写法 list.sort((i1, i2) -> i1 - i2); ``` - **示例 2:单参数 ...
cmd.CommandText = string.Format( "INSERT INTO INDIVIDUAL (ID, FIRSTNAME, MIDDLENAME, LASTNAME, DOB, STATE) VALUES({0}, '{1}', '{2}', '{3}', '{4}', '{5}');", id, firstname, middlename, ...
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. ...
String formatted = String.format("Name: %s, Age: %d", "John Doe", 25); System.out.println(formatted); ``` ### 10. 访问修饰符 `protected` - **定义**:`protected` 访问修饰符使得成员对同一包内的类...
* string:字符串 * character:字符 * integer:整数 * boolean:布尔 * true:真 * false:假 控制结构 * if:如果 * else:否则 * case:案例 * default:默认 * switch:开关 * break:中断 * match:匹配 * ...
[Compare("Email", ErrorMessage = "确认邮箱必须与邮箱一致")] public string TEmail { get; set; } [Display(Name = "身份证号")] [RegularExpression(@"\d{17}[\d|x]|\d{15}", ErrorMessage = "身份证号格式...
"Numerically Aware String Compare"是一种特殊的字符串比较算法,它在处理包含数字的字符串时能更好地遵循人类的自然排序逻辑。这种算法确保了当我们在比较如"A1", "A2", "A10"这样的字符串时,可以按照数字的大小...