String.Compare 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
지정된 두 String 개체를 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
오버로드
| Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) |
지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 부분 문자열 간의 관계를 나타내는 정수를 반환합니다. 지정된 비교 옵션 및 문화권별 정보가 비교에 영향을 줍니다. |
| Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) |
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체의 부분 문자열을 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. 문화권별 정보가 비교에 영향을 줍니다. |
| Compare(String, Int32, String, Int32, Int32, StringComparison) |
지정된 규칙을 사용하여 지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, Int32, String, Int32, Int32, Boolean) |
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체의 부분 문자열을 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, Int32, String, Int32, Int32) |
지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, String) |
지정된 두 String 개체를 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, String, Boolean, CultureInfo) |
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체를 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. 문화권별 정보가 비교에 영향을 줍니다. |
| Compare(String, String, StringComparison) |
지정된 규칙을 사용하여 지정된 두 String 개체를 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, String, Boolean) |
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체를 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. |
| Compare(String, String, CultureInfo, CompareOptions) |
지정된 두 String 개체를 비교하고 정렬 순서에서 두 문자열 간의 관계를 나타내는 정수를 반환합니다. 지정된 비교 옵션 및 문화권별 정보가 비교에 영향을 줍니다. |
설명
Compare 메서드의 모든 오버로드는 두 비교 대상 간의 어휘 관계를 나타내는 부호 있는 32비트 정수를 반환합니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | 첫 번째 하위 문자열은 정렬 순서에서 두 번째 부분 문자열 앞에 옵니다. |
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length가 0인 경우 |
| 0보다 큼 | 첫 번째 부분 문자열은 정렬 순서에서 두 번째 부분 문자열 뒤에 옵니다. |
경고
가능 하면 Compare 매개 변수를 포함 하는 메서드의 오버 로드를 호출 해야 합니다 StringComparison . 자세한 내용은 문자열 사용에 대한 모범 사례를 참조하세요.
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)
지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 부분 문자열 간의 관계를 나타내는 정수를 반환합니다. 지정된 비교 옵션 및 문화권별 정보가 비교에 영향을 줍니다.
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * int * string * int * int * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, culture As CultureInfo, options As CompareOptions) As Integer
매개 변수
- strA
- String
비교에 사용할 첫 번째 문자열입니다.
- indexA
- Int32
strA에 있는 부분 문자열의 시작 위치입니다.
- strB
- String
비교에 사용할 두 번째 문자열입니다.
- indexB
- Int32
strB에 있는 부분 문자열의 시작 위치입니다.
- length
- Int32
비교할 부분 문자열의 최대 문자 수입니다.
- culture
- CultureInfo
문화권별 비교 정보를 제공하는 개체입니다. culture가 null이면 현재 문화권이 사용됩니다.
- options
- CompareOptions
대/소문자 또는 기호 무시 여부와 같이 비교를 수행할 때 사용할 옵션입니다.
반환
다음 표와 같이 두 부분 문자열 간의 어휘 관계를 나타내는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 앞에 오는 경우
|
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length가 0인 경우
|
| 0보다 큼 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 다음에 오는 경우
|
예외
options이 CompareOptions 값이 아닙니다.
indexA가 strA.Length보다 큽니다.
또는
indexB가 strB.Length보다 큽니다.
또는
indexA, indexB 또는 length가 음수입니다.
또는
strA 또는 strB가 null이고 length가 0보다 큽니다.
예제
다음 예제에서는 메서드를 사용 하 여 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 두 사람의 성을 비교 합니다. 그런 다음 알파벳 순서로 나열 합니다.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string name1 = "Jack Smith";
string name2 = "John Doe";
// Get position of character after the space character.
int index1 = name1.IndexOf(" ");
index1 = index1 < 0 ? 0 : ++index1;
int index2 = name2.IndexOf(" ");
index2 = index2 < 0 ? 0 : ++index2;
int length = Math.Max(name1.Length, name2.Length);
Console.WriteLine("Sorted alphabetically by last name:");
if (String.Compare(name1, index1, name2, index2, length,
new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
Console.WriteLine("{0}\n{1}", name1, name2);
else
Console.WriteLine("{0}\n{1}", name2, name1);
}
}
// The example displays the following output:
// Sorted alphabetically by last name:
// John Doe
// Jack Smith
Imports System.Globalization
Module Example
Public Sub Main()
Dim name1 As String = "Jack Smith"
Dim name2 = "John Doe"
' Get position of space character.
Dim index1 As Integer = name1.IndexOf(" ")
index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
Dim index2 As Integer = name2.IndexOf(" ")
index1 = CInt(IIf(index1 < 0, 0, index1 - 1))
Dim length As Integer = Math.Max(name1.Length, name2.Length)
Console.WriteLIne("Sorted alphabetically by last name:")
If String.Compare(name1, index1, name2, index2, length, _
New CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0 Then
Console.WriteLine("{0}{1}{2}", name1, vbCrLf, name2)
Else
Console.WriteLine("{0}{1}{2}", name2, vbCrLf, name1)
End If
End Sub
End Module
' The example displays the following output;
' Sorted alphabetically by last name:
' John Doe
' Jack Smith
설명
비교할 부분 문자열 ( strA 위치 및 위치) indexA strB indexB 입니다. 첫 번째 부분 문자열의 길이는 마이너스의 길이 strA 입니다 indexA . 두 번째 부분 문자열의 길이는 마이너스의 길이 strB 입니다 indexB .
비교할 문자 수는 두 부분 문자열의 길이 중 더 작은 값입니다 length . indexA, indexB 및 length 매개 변수는 음수가 아니어야 합니다.
비교는 매개 변수를 사용 하 여 culture 대/소문자 규칙 및 개별 문자의 알파벳 순서와 같은 문화권 관련 정보를 가져옵니다. 예를 들어 특정 문화권은 특정 문자 조합을 단일 문자로 처리 하거나, 대문자 및 소문자를 특정 방식으로 비교 하거나, 문자의 앞 이나 뒤에 오는 문자에 따라 문자의 정렬 순서가 달라 지는 것을 지정할 수 있습니다.
주의
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)메서드는 주로 정렬 또는 사전순 작업에 사용할 수 있도록 디자인 되었습니다. 메서드 호출의 기본 목적이 두 부분 문자열이 같은지 여부를 확인 하는 경우 (즉, 메서드 호출의 목적이 반환 값 0을 테스트 하는 경우)에는이 메서드를 사용 하면 안 됩니다. 두 문자열이 같은지 여부를 확인 하려면 메서드를 호출 Equals 합니다.
및 중 하나는 strA strB 일 수 있습니다 null . 정의에 따라,를 포함 하는 모든 문자열 String.Empty 은 null 참조 보다 큰 값을 비교 하 고 두 개의 null 참조는 서로 비교 합니다.
options열거형의 하나 이상의 멤버로 구성 된 매개 변수를 통해 비교를 추가로 지정할 수 있습니다 System.Globalization.CompareOptions . 그러나이 메서드는 문화권을 구분 하는 문자열 비교를 수행 하기 위한 것 이므로 및 값은 아무런 영향을 주지 CompareOptions.Ordinal CompareOptions.OrdinalIgnoreCase 않습니다.
같지 않음이 검색 되거나 두 부분 문자열이 비교 되 면 비교가 종료 됩니다. 그러나 두 문자열이 한 문자열의 끝과 동일한 것으로 간주 되 고 다른 문자열에 문자가 남아 있으면 나머지 문자를 포함 하는 문자열이 더 큰 것으로 간주 됩니다. 반환 값은 마지막으로 수행 된 비교의 결과입니다.
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)언어 또는 문화권 구분 비교를 수행 하는 경우 메서드는 이러한 문자를 고려 하지 않습니다. 비교에서 무시할 수 있는 문자를 인식 하려면 Ordinal 매개 변수에 대해 또는 값을 제공 OrdinalIgnoreCase options 합니다.
추가 정보
적용 대상
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체의 부분 문자열을 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. 문화권별 정보가 비교에 영향을 줍니다.
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * int * string * int * int * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean, culture As CultureInfo) As Integer
매개 변수
- strA
- String
비교에 사용할 첫 번째 문자열입니다.
- indexA
- Int32
strA에 있는 부분 문자열의 위치입니다.
- strB
- String
비교에 사용할 두 번째 문자열입니다.
- indexB
- Int32
strB에 있는 부분 문자열의 위치입니다.
- length
- Int32
비교할 부분 문자열의 최대 문자 수입니다.
- ignoreCase
- Boolean
비교 시 대/소문자를 무시하려면 true이고, 그러지 않으면 false입니다.
- culture
- CultureInfo
문화권별 비교 정보를 제공하는 개체입니다. culture가 null이면 현재 문화권이 사용됩니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 앞에 오는 경우
|
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length가 0인 경우
|
| 0보다 큼 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 다음에 오는 경우
|
예외
indexA가 strA.Length보다 큽니다.
또는
indexB가 strB.Length보다 큽니다.
또는
indexA, indexB 또는 length가 음수입니다.
또는
strA 또는 strB가 null이고 length가 0보다 큽니다.
예제
다음 예제에서는 서로 다른 문화권을 사용 하는 두 부분 문자열을 비교 하 고 부분 문자열의 대/소문자를 무시 합니다. 문화권 선택은 문자 "I"의 비교 방법에 영향을 줍니다.
// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using namespace System;
using namespace System::Globalization;
int main()
{
// 0123456
String^ str1 = "MACHINE";
String^ str2 = "machine";
String^ str;
int result;
Console::WriteLine();
Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
Console::WriteLine( "Ignore case, Turkish culture:" );
result = String::Compare( str1, 4, str2, 4, 2, true, gcnew CultureInfo( "tr-TR" ) );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 4, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 4, 2 ), str2 );
Console::WriteLine();
Console::WriteLine( "Ignore case, invariant culture:" );
result = String::Compare( str1, 4, str2, 4, 2, true, CultureInfo::InvariantCulture );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 4, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 4, 2 ), str2 );
}
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
// Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using System;
using System.Globalization;
class Sample5
{
public static void Main()
{
// 0123456
String str1 = "MACHINE";
String str2 = "machine";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case, Turkish culture:");
result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
Console.WriteLine();
Console.WriteLine("Ignore case, invariant culture:");
result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
}
}
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
Imports System.Globalization
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "MACHINE"
Dim str2 As [String] = "machine"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
Console.WriteLine("Ignore case, Turkish culture:")
result = [String].Compare(str1, 4, str2, 4, 2, True, New CultureInfo("tr-TR"))
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
Console.WriteLine()
Console.WriteLine("Ignore case, invariant culture:")
result = [String].Compare(str1, 4, str2, 4, 2, True, CultureInfo.InvariantCulture)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case, Turkish culture:
'Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.
'
'Ignore case, invariant culture:
'Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
'
설명
비교할 부분 문자열은에서 시작 하 고,에서는로 시작 strA indexA strB indexB 합니다. 와는 모두 indexA indexB 0부터 시작 합니다. 즉, 및의 첫 번째 문자는 strA strB 위치가 0이 아닌 0 위치에 있습니다. 첫 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strA indexA . 두 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strB indexB .
비교할 문자 수는 두 부분 문자열의 길이 중 더 작은 값입니다 length . indexA, indexB 및 length 매개 변수는 음수가 아니어야 합니다.
비교는 매개 변수를 사용 하 여 culture 대/소문자 규칙 및 개별 문자의 알파벳 순서와 같은 문화권 관련 정보를 가져옵니다. 예를 들어 문화권은 문자의 특정 조합이 단일 문자로 처리 되도록 지정 하거나, 대문자 및 소문자를 특정 방식으로 비교 하거나, 문자의 앞 이나 뒤에 오는 문자에 따라 문자의 정렬 순서가 달라 지는 것을 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용 하 여 수행 됩니다. 단어, 문자열 및 서 수 정렬에 대 한 자세한 내용은을 참조 하십시오 System.Globalization.CompareOptions .
하나 또는 두 비교는 모두 일 수 있습니다 null . 정의에 따라 빈 문자열 ("")을 포함 하는 모든 문자열은 null 참조 보다 큰 값을 비교 합니다. 및 두 개의 null 참조가 서로 같은지 비교 합니다.
같지 않음이 검색 되거나 두 부분 문자열이 비교 되 면 비교가 종료 됩니다. 그러나 두 문자열이 한 문자열의 끝과 동일한 것으로 간주 되 고 다른 문자열에 문자가 남아 있으면 나머지 문자를 포함 하는 문자열이 더 큰 것으로 간주 됩니다. 반환 값은 마지막으로 수행 된 비교의 결과입니다.
문화권별 대/소문자 규칙에 따라 비교가 영향을 받는 경우 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 파일 시스템은 "file"의 문자 "i"에 대 한 언어 대/소문자 규칙을 사용 하지 않으므로 터키어에서 다음 예제는 잘못 된 결과를 생성 합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서 수 비교를 사용 하 여 경로 이름을 "file"과 비교 합니다. 이 작업을 수행 하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)언어 또는 문화권 구분 비교를 수행 하는 경우 메서드는 이러한 문자를 고려 하지 않습니다. 비교에서 무시할 수 있는 문자를 인식 하려면 메서드를 호출 하 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 고 매개 변수에 또는의 값을 제공 Ordinal OrdinalIgnoreCase options 합니다.
추가 정보
적용 대상
Compare(String, Int32, String, Int32, Int32, StringComparison)
지정된 규칙을 사용하여 지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, StringComparison comparisonType);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType);
static member Compare : string * int * string * int * int * StringComparison -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, comparisonType As StringComparison) As Integer
매개 변수
- strA
- String
비교에 사용할 첫 번째 문자열입니다.
- indexA
- Int32
strA에 있는 부분 문자열의 위치입니다.
- strB
- String
비교에 사용할 두 번째 문자열입니다.
- indexB
- Int32
strB에 있는 부분 문자열의 위치입니다.
- length
- Int32
비교할 부분 문자열의 최대 문자 수입니다.
- comparisonType
- StringComparison
비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 앞에 오는 경우
|
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length 매개 변수가 0인 경우
|
| 0보다 큼 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 다음에 오는 경우
|
예외
indexA가 strA.Length보다 큽니다.
또는
indexB가 strB.Length보다 큽니다.
또는
indexA, indexB 또는 length가 음수입니다.
또는
indexA 또는 indexB가 null이고 length가 0보다 큽니다.
comparisonType이 StringComparison 값이 아닙니다.
예제
다음 예제에서는 두 개의 부분 문자열을 비교 합니다.
// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
// 0123456
String^ str1 = "machine";
String^ str2 = "device";
String^ str;
int result;
Console::WriteLine();
Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
result = String::Compare( str1, 2, str2, 0, 2 );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in ' {1}' is ", str1->Substring( 2, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in ' {1}'.", str2->Substring( 0, 2 ), str2 );
}
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
String str1 = "machine";
String str2 = "device";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "machine"
Dim str2 As [String] = "device"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
result = [String].Compare(str1, 2, str2, 0, 2)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'
설명
비교할 부분 문자열은에서 시작 하 고에서 시작 strA indexA strB indexB 합니다. 와는 모두 indexA indexB 0부터 시작 합니다. 즉, 및의 첫 번째 문자는 strA strB 위치가 0이 아닌 0 위치에 있습니다. 첫 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strA indexA . 두 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strB indexB .
비교할 문자 수는 두 부분 문자열의 길이 중 더 작은 값입니다 length . indexA, indexB 및 length 매개 변수는 음수가 아니어야 합니다.
comparisonType매개 변수는 비교 시 현재 또는 고정 문화권을 사용 해야 하는지 여부를 지정 하 고, 비교의 대/소문자를 무시 하거나 무시 하거나, 단어 (문화권 구분) 또는 서 수 (문화권 구분 안 함) 정렬 규칙을 사용 합니다.
하나 또는 두 비교는 모두 일 수 있습니다 null . 정의에 따라 빈 문자열 ("")을 포함 하는 모든 문자열은 null 참조 보다 큰 값을 비교 합니다. 및 두 개의 null 참조가 서로 같은지 비교 합니다.
같지 않음이 검색 되거나 두 부분 문자열이 비교 되 면 비교가 종료 됩니다. 그러나 두 문자열이 한 문자열의 끝과 동일한 것으로 간주 되 고 다른 문자열에 문자가 남아 있으면 나머지 문자를 포함 하는 문자열이 더 큰 것으로 간주 됩니다. 반환 값은 마지막으로 수행 된 비교의 결과입니다.
문화권별 대/소문자 규칙에 따라 비교가 영향을 받는 경우 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 파일 시스템은 "file"의 문자 "i"에 대 한 언어 대/소문자 규칙을 사용 하지 않으므로 터키어에서 다음 예제는 잘못 된 결과를 생성 합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서 수 비교를 사용 하 여 경로 이름을 "file"과 비교 합니다. 이 작업을 수행 하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, Int32, String, Int32, Int32, StringComparison)언어 또는 문화권 구분 비교를 수행 하는 경우 메서드는 이러한 문자를 고려 하지 않습니다. 비교에서 무시할 수 있는 문자를 인식 하려면 Ordinal 매개 변수에 대해 또는 값을 제공 OrdinalIgnoreCase comparisonType 합니다.
추가 정보
적용 대상
Compare(String, Int32, String, Int32, Int32, Boolean)
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체의 부분 문자열을 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
static member Compare : string * int * string * int * int * bool -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean) As Integer
매개 변수
- strA
- String
비교에 사용할 첫 번째 문자열입니다.
- indexA
- Int32
strA에 있는 부분 문자열의 위치입니다.
- strB
- String
비교에 사용할 두 번째 문자열입니다.
- indexB
- Int32
strB에 있는 부분 문자열의 위치입니다.
- length
- Int32
비교할 부분 문자열의 최대 문자 수입니다.
- ignoreCase
- Boolean
비교 시 대/소문자를 무시하려면 true이고, 그러지 않으면 false입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 앞에 오는 경우
|
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length가 0인 경우
|
| 0보다 큼 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 다음에 오는 경우
|
예외
indexA가 strA.Length보다 큽니다.
또는
indexB가 strB.Length보다 큽니다.
또는
indexA, indexB 또는 length가 음수입니다.
또는
indexA 또는 indexB가 null이고 length가 0보다 큽니다.
예제
다음 예제에서는 대/소문자만 다른 두 부분 문자열의 두 비교를 수행 합니다. 첫 번째 비교는 대 소문자를 무시 하 고 두 번째 비교는 대/소문자를 고려 합니다.
// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean)
using namespace System;
int main()
{
// 0123456
String^ str1 = "MACHINE";
String^ str2 = "machine";
String^ str;
int result;
Console::WriteLine();
Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
Console::WriteLine( "Ignore case:" );
result = String::Compare( str1, 2, str2, 2, 2, true );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 2, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 2, 2 ), str2 );
Console::WriteLine();
Console::WriteLine( "Honor case:" );
result = String::Compare( str1, 2, str2, 2, 2, false );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in '{1}' is ", str1->Substring( 2, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in '{1}'.", str2->Substring( 2, 2 ), str2 );
}
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
String str1 = "MACHINE";
String str2 = "machine";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case:");
result = String.Compare(str1, 2, str2, 2, 2, true);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
Console.WriteLine();
Console.WriteLine("Honor case:");
result = String.Compare(str1, 2, str2, 2, 2, false);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
/*
This example produces the following results:
str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32, Boolean)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "MACHINE"
Dim str2 As [String] = "machine"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
Console.WriteLine("Ignore case:")
result = [String].Compare(str1, 2, str2, 2, 2, True)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
Console.WriteLine()
Console.WriteLine("Honor case:")
result = [String].Compare(str1, 2, str2, 2, 2, False)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'MACHINE', str2 = 'machine'
'Ignore case:
'Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.
'
'Honor case:
'Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
'
설명
비교할 부분 문자열은에서 시작 하 고,에서는로 시작 strA indexA strB indexB 합니다. 와는 모두 indexA indexB 0부터 시작 합니다. 즉,의 첫 번째 문자 strA 는 strB 위치 0에 있습니다. 첫 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strA indexA . 두 번째 부분 문자열의 길이는의 길이에서 1을 더한 값과 같습니다 strB indexB .
비교할 문자 수는 두 부분 문자열의 길이 중 더 작은 값입니다 length . indexA, indexB 및 length 매개 변수는 음수가 아니어야 합니다.
비교에서는 현재 문화권을 사용 하 여 대/소문자 규칙 및 개별 문자의 알파벳 순서와 같은 문화권 관련 정보를 가져옵니다. 예를 들어 문화권은 문자의 특정 조합이 단일 문자로 처리 되도록 지정 하거나, 대문자 및 소문자를 특정 방식으로 비교 하거나, 문자의 앞 이나 뒤에 오는 문자에 따라 문자의 정렬 순서가 달라 지는 것을 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용 하 여 수행 됩니다. 단어, 문자열 및 서 수 정렬에 대 한 자세한 내용은을 참조 하십시오 System.Globalization.CompareOptions .
경고
문자열을 비교할 때 메서드를 호출 해야 합니다 .이 경우 Compare(String, Int32, String, Int32, Int32, StringComparison) 메서드에서 사용 하는 문자열 비교의 형식을 명시적으로 지정 해야 합니다. 자세한 내용은 문자열 사용에 대한 모범 사례를 참조하세요.
하나 또는 두 비교는 모두 일 수 있습니다 null . 정의에 따라 빈 문자열 ("")을 포함 하는 모든 문자열은 null 참조 보다 큰 값을 비교 합니다. 및 두 개의 null 참조가 서로 같은지 비교 합니다.
같지 않음이 검색 되거나 두 부분 문자열이 비교 되 면 비교가 종료 됩니다. 그러나 두 문자열이 한 문자열의 끝과 동일한 것으로 간주 되 고 다른 문자열에 문자가 남아 있으면 나머지 문자를 포함 하는 문자열이 더 큰 것으로 간주 됩니다. 반환 값은 마지막으로 수행 된 비교의 결과입니다.
문화권별 대/소문자 규칙에 따라 비교가 영향을 받는 경우 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 파일 시스템은 "file"의 문자 "i"에 대 한 언어 대/소문자 규칙을 사용 하지 않으므로 터키어에서 다음 예제는 잘못 된 결과를 생성 합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
경로 이름은 고정 방식으로 비교 해야 합니다. 이 작업을 수행 하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, Int32, String, Int32, Int32, Boolean)언어 또는 문화권 구분 비교를 수행 하는 경우 메서드는 이러한 문자를 고려 하지 않습니다. 비교에서 무시할 수 있는 문자를 인식 하려면 메서드를 호출 하 Compare(String, Int32, String, Int32, Int32, StringComparison) 고 매개 변수에 또는의 값을 제공 Ordinal OrdinalIgnoreCase comparisonType 합니다.
추가 정보
적용 대상
Compare(String, Int32, String, Int32, Int32)
지정된 두 String 개체의 부분 문자열을 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public static int Compare (string strA, int indexA, string strB, int indexB, int length);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length);
static member Compare : string * int * string * int * int -> int
Public Shared Function Compare (strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer) As Integer
매개 변수
- strA
- String
비교에 사용할 첫 번째 문자열입니다.
- indexA
- Int32
strA에 있는 부분 문자열의 위치입니다.
- strB
- String
비교에 사용할 두 번째 문자열입니다.
- indexB
- Int32
strB에 있는 부분 문자열의 위치입니다.
- length
- Int32
비교할 부분 문자열의 최대 문자 수입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 부호 있는 32비트 정수를 반환합니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 앞에 오는 경우
|
| 0 | 부분 문자열이 정렬 순서에서 같은 위치에 나오거나 length가 0인 경우
|
| 0보다 큼 | strA의 부분 문자열이 정렬 순서에서 strB의 부분 문자열 다음에 오는 경우
|
예외
indexA가 strA.Length보다 큽니다.
또는
indexB가 strB.Length보다 큽니다.
또는
indexA, indexB 또는 length가 음수입니다.
또는
indexA 또는 indexB가 null이고 length가 0보다 큽니다.
예제
다음 예제에서는 두 부분스트링을 비교합니다.
// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main()
{
// 0123456
String^ str1 = "machine";
String^ str2 = "device";
String^ str;
int result;
Console::WriteLine();
Console::WriteLine( "str1 = '{0}', str2 = '{1}'", str1, str2 );
result = String::Compare( str1, 2, str2, 0, 2 );
str = ((result < 0) ? "less than" : ((result > 0) ? (String^)"greater than" : "equal to"));
Console::Write( "Substring '{0}' in ' {1}' is ", str1->Substring( 2, 2 ), str1 );
Console::Write( " {0} ", str );
Console::WriteLine( "substring '{0}' in ' {1}'.", str2->Substring( 0, 2 ), str2 );
}
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
String str1 = "machine";
String str2 = "device";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
/*
This example produces the following results:
str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
' Sample for String.Compare(String, Int32, String, Int32, Int32)
Class Sample
Public Shared Sub Main()
' 0123456
Dim str1 As [String] = "machine"
Dim str2 As [String] = "device"
Dim str As [String]
Dim result As Integer
Console.WriteLine()
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2)
result = [String].Compare(str1, 2, str2, 0, 2)
str = IIf(result < 0, "less than", IIf(result > 0, "greater than", "equal to"))
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1)
Console.Write("{0} ", str)
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2)
End Sub
End Class
'
'This example produces the following results:
'
'str1 = 'machine', str2 = 'device'
'Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
'
설명
비교할 부분strings는 에서 시작하고 에서 strA indexA strB indexB 시작합니다. 및 는 둘 다 indexA indexB 0 기반입니다. 즉, 및 의 첫 번째 strA strB 문자가 위치 0에 있습니다. 첫 번째 부분string의 길이는 빼기 및 1의 길이와 strA indexA 같습니다. 두 번째 부분string의 길이는 strB 길이에서 1을 더한 값과 indexB 같습니다.
비교할 문자 수는 및 의 두 부분 문자 길이보다 length 작습니다. indexA, indexB 및 length 매개 변수는 피연산자여야 합니다.
비교에서는 현재 문화권을 사용하여 대/소문자 구분 규칙 및 개별 문자의 사전순과 같은 문화권별 정보를 얻습니다. 예를 들어 문화권은 특정 문자 조합을 단일 문자로 처리하거나 대문자와 소문자를 특정 방식으로 비교하도록 지정하거나 문자의 정렬 순서가 앞이나 뒤에 오는 문자에 따라 달라지도록 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용하여 수행됩니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 를 System.Globalization.CompareOptions 참조하세요.
경고
문자열을 비교할 때 메서드를 호출해야 합니다. 이 Compare(String, Int32, String, Int32, Int32, StringComparison) 경우 메서드에서 사용하는 문자열 비교 형식을 명시적으로 지정해야 합니다. 자세한 내용은 문자열 사용에 대한 모범 사례를 참조하세요.
하나 또는 두 비교는 일 수 null 있습니다. 정의에 따라 빈 문자열("")을 포함한 모든 문자열은 null 참조보다 큰 문자열을 비교합니다. 두 null 참조는 서로 비교됩니다.
다른 부분의 다른 부분만 검색되거나 두 부분의 부분 부분만 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다. 반환 값은 수행된 마지막 비교의 결과입니다.
문화권별 대/소문자 구분 규칙의 영향을 받는 비교 시 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 다음 예제에서는 터키어의 파일 시스템이 "file"의 문자 "i"에 대해 언어 대/소문자 규칙을 사용하지 않기 때문에 잘못된 결과를 산출합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서수 비교를 사용하여 경로 이름을 "file"과 비교합니다. 이 작업을 수행하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, Int32, String, Int32, Int32)언어 또는 문화권 구분 비교를 수행 하는 경우 메서드는 이러한 문자를 고려 하지 않습니다. 비교에서 무시할 수 있는 문자를 인식 하려면 메서드를 호출 하 Compare(String, Int32, String, Int32, Int32, StringComparison) 고 매개 변수에 또는의 값을 제공 Ordinal OrdinalIgnoreCase comparisonType 합니다.
추가 정보
적용 대상
Compare(String, String)
지정된 두 String 개체를 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, System::String ^ strB);
public static int Compare (string strA, string strB);
public static int Compare (string? strA, string? strB);
static member Compare : string * string -> int
Public Shared Function Compare (strA As String, strB As String) As Integer
매개 변수
- strA
- String
비교할 첫째 문자열입니다.
- strB
- String
비교할 둘째 문자열입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA 가 정렬 순서에서 strB 앞에 오는 경우
|
| 0 | strA가 정렬 순서에서 strB와 동일한 위치에서 발생합니다.
|
| 0보다 큼 | strA가 정렬 순서에서 strB 뒤에 오는 경우
|
예제
다음 예제에서는 Compare(String, String) 메서드를 호출하여 세 개의 문자열 집합을 비교합니다.
using namespace System;
void main()
{
// Create upper-case characters from their Unicode code units.
String^ stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String^ stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console::WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console::WriteLine("The Strings are equal when capitalized? {0}",
String::Compare(stringUpper->ToUpper(), stringLower->ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console::WriteLine("The Strings are equal when case is ignored? {0}",
String::Compare(stringUpper, stringLower, true) == 0
? "true" : "false");
}
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
String.Compare(stringUpper, stringLower, true) == 0
? "true" : "false" );
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
Public Module Example
Public Sub Main()
' Create upper-case characters from their Unicode code units.
Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)
' Create lower-case characters from their Unicode code units.
Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)
' Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower)
' Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
If(String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0,
"true", "false"))
' The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
If(String.Compare(stringUpper, stringLower, true) = 0,
"true", "false"))
End Sub
End Module
' The example displays the following output:
' Comparing 'ABC' and 'abc':
' The Strings are equal when capitalized? true
' The Strings are equal when case is ignored? true
다음 예제에서 ReverseStringComparer 클래스는 메서드를 사용하여 두 문자열을 평가하는 방법을 Compare 보여줍니다.
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 ));
}
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);
}
}
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
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
End Class
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
설명
비교에서는 현재 문화권을 사용하여 대/소문자 구분 규칙 및 개별 문자의 사전순과 같은 문화권별 정보를 얻습니다. 예를 들어 문화권은 특정 문자 조합을 단일 문자로 처리하거나 대문자와 소문자를 특정 방식으로 비교하도록 지정하거나 문자의 정렬 순서가 앞이나 뒤에 오는 문자에 따라 달라지도록 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용하여 수행됩니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 를 System.Globalization.CompareOptions 참조하세요.
경고
문자열을 비교할 때 메서드를 호출해야 합니다. 이 Compare(String, String, StringComparison) 경우 메서드에서 사용하는 문자열 비교 형식을 명시적으로 지정해야 합니다. 자세한 내용은 문자열 사용에 대한 모범 사례를 참조하세요.
하나 또는 두 비교는 일 수 null 있습니다. 정의에 따라 빈 문자열("")을 포함한 모든 문자열은 null 참조보다 큰 문자열을 비교합니다. 두 null 참조는 서로 비교됩니다.
다른 문자열이 검색되거나 두 문자열을 모두 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다. 반환 값은 수행된 마지막 비교의 결과입니다.
문화권별 대/소문자 구분 규칙의 영향을 받는 비교 시 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 다음 예제에서는 터키어의 파일 시스템이 "file"의 문자 "i"에 대해 언어 대/소문자 규칙을 사용하지 않기 때문에 잘못된 결과를 산출합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서수 비교를 사용하여 경로 이름을 "file"과 비교합니다. 이 작업을 수행하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, String)메서드는 문화권 구분 비교를 수행할 때 이러한 문자를 고려하지 않습니다. 예를 들어 다음 코드가 .NET Framework 4 이상에서 실행되는 경우 "동물"과 "ani-mal"(소프트 하이픈 또는 U+00AD 사용)의 문화권 구분 비교는 두 문자열이 동일함을 나타냅니다.
문자열 비교에서 무시 가능한 문자를 인식하려면 Compare(String, String, StringComparison) 메서드를 호출하고 매개 변수에 대해 또는 값을 Ordinal 입력합니다. OrdinalIgnoreCase comparisonType
추가 정보
적용 대상
Compare(String, String, Boolean, CultureInfo)
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체를 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다. 문화권별 정보가 비교에 영향을 줍니다.
public:
static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare (string? strA, string? strB, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare (string strA, string strB, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * string * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean, culture As CultureInfo) As Integer
매개 변수
- strA
- String
비교할 첫째 문자열입니다.
- strB
- String
비교할 둘째 문자열입니다.
- ignoreCase
- Boolean
비교 시 대/소문자를 무시하려면 true이고, 그러지 않으면 false입니다.
- culture
- CultureInfo
문화권별 비교 정보를 제공하는 개체입니다. culture가 null이면 현재 문화권이 사용됩니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA 가 정렬 순서에서 strB 앞에 오는 경우
|
| 0 | strA가 정렬 순서에서 strB와 동일한 위치에서 발생합니다.
|
| 0보다 큼 | strA가 정렬 순서에서 strB 뒤에 오는 경우
|
예제
다음 예제에서는 문화권이 비교에 영향을 줄 수 있는 방법을 보여 있습니다. 체코어 - 체코 공화국 문화권에서 "ch"는 "d"보다 큰 단일 문자입니다. 그러나 영어 - 미국 문화권에서 "ch"는 두 문자로 구성되고 "c"는 "d"보다 적습니다.
using namespace System;
using namespace System::Globalization;
String^ symbol( int r )
{
String^ s = "=";
if ( r < 0 )
s = "<";
else
if ( r > 0 )
s = ">";
return s;
}
int main()
{
String^ str1 = "change";
String^ str2 = "dollar";
String^ relation = nullptr;
relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "en-US" ) ) );
Console::WriteLine( "For en-US: {0} {1} {2}", str1, relation, str2 );
relation = symbol( String::Compare( str1, str2, false, gcnew CultureInfo( "cs-CZ" ) ) );
Console::WriteLine( "For cs-CZ: {0} {1} {2}", str1, relation, str2 );
}
/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
public static void Main()
{
String str1 = "change";
String str2 = "dollar";
String relation = null;
relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US")));
Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2);
relation = symbol(String.Compare(str1, str2, false, new CultureInfo("cs-CZ")));
Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2);
}
private static String symbol(int r)
{
String s = "=";
if (r < 0) s = "<";
else if (r > 0) s = ">";
return s;
}
/*
This example produces the following results.
For en-US: change < dollar
For cs-CZ: change > dollar
*/
Imports System.Globalization
_
Class Sample
Public Shared Sub Main()
Dim str1 As [String] = "change"
Dim str2 As [String] = "dollar"
Dim relation As [String] = Nothing
relation = symbol([String].Compare(str1, str2, False, New CultureInfo("en-US")))
Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2)
relation = symbol([String].Compare(str1, str2, False, New CultureInfo("cs-CZ")))
Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2)
End Sub
Private Shared Function symbol(r As Integer) As [String]
Dim s As [String] = "="
If r < 0 Then
s = "<"
Else
If r > 0 Then
s = ">"
End If
End If
Return s
End Function 'symbol
End Class
'
'This example produces the following results.
'For en-US: change < dollar
'For cs-CZ: change > dollar
'
설명
비교에서는 매개 변수를 사용하여 culture 대/소문자 구분 규칙 및 개별 문자의 사전순과 같은 문화권별 정보를 얻습니다. 예를 들어 문화권은 특정 문자 조합을 단일 문자로 처리하거나 대문자와 소문자를 특정 방식으로 비교하도록 지정하거나 문자의 정렬 순서가 앞이나 뒤에 오는 문자에 따라 달라지도록 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용하여 수행됩니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 를 System.Globalization.CompareOptions 참조하세요.
하나 또는 두 비교는 일 수 null 있습니다. 정의에 따라 빈 문자열("")을 포함한 모든 문자열은 null 참조보다 큰 문자열을 비교합니다. 두 null 참조는 서로 비교됩니다.
다른 문자열이 검색되거나 두 문자열을 모두 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다. 반환 값은 수행된 마지막 비교의 결과입니다.
문화권별 대/소문자 구분 규칙의 영향을 받는 비교 시 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 다음 예제에서는 터키어의 파일 시스템이 "file"의 문자 "i"에 대해 언어 대/소문자 규칙을 사용하지 않기 때문에 잘못된 결과를 산출합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서수 비교를 사용하여 경로 이름을 "file"과 비교합니다. 이 작업을 수행하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, String, Boolean, CultureInfo)메서드는 문화권 구분 비교를 수행할 때 이러한 문자를 고려하지 않습니다. 예를 들어 다음 코드가 .NET Framework 4 이상에서 실행되는 경우 고정 문화권에서 "동물"을 "Ani-mal"(소프트 하이픈 사용 또는 U+00AD 사용)과 대/소문자를 구분하지 않는 비교는 두 문자열이 동일함을 나타냅니다.
문자열 비교에서 무시 가능한 문자를 인식하려면 Compare(String, String, CultureInfo, CompareOptions) 메서드를 호출하고 매개 변수에 대해 또는 값을 Ordinal 입력합니다. OrdinalIgnoreCase options
추가 정보
- Int32
- CompareOrdinal(String, String)
- CompareTo(Object)
- IsPrefix(String, String, CompareOptions)
- Boolean
적용 대상
Compare(String, String, StringComparison)
지정된 규칙을 사용하여 지정된 두 String 개체를 비교하고 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, System::String ^ strB, StringComparison comparisonType);
public static int Compare (string strA, string strB, StringComparison comparisonType);
public static int Compare (string? strA, string? strB, StringComparison comparisonType);
static member Compare : string * string * StringComparison -> int
Public Shared Function Compare (strA As String, strB As String, comparisonType As StringComparison) As Integer
매개 변수
- strA
- String
비교할 첫째 문자열입니다.
- strB
- String
비교할 둘째 문자열입니다.
- comparisonType
- StringComparison
비교에 사용할 규칙을 지정하는 열거형 값 중 하나입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA 가 정렬 순서에서 strB 앞에 오는 경우
|
| 0 | strA가 정렬 순서에서 strB와 동일한 위치에 있는 경우
|
| 0보다 큼 | strA가 정렬 순서에서 strB 뒤에 오는 경우
|
예외
comparisonType이 StringComparison 값이 아닙니다.
StringComparison은 지원되지 않습니다.
예제
다음 예제에서는 문자 "I"의 세 가지 버전을 비교합니다. 결과는 문화권 선택, 대/소문자 무시 여부 및 서수 비교 수행 여부의 영향을 받습니다.
// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.
using namespace System;
using namespace System::Threading;
void Test(int testStringIndex, int searchStringIndex,
StringComparison comparison, array<String^>^ testI,
array<String^>^ testNames)
{
String^ resultFormat = "{0} is {1} {2}";
String^ resultString = "equal to";
int comparisonValue = 0;
comparisonValue = String::Compare(testI[testStringIndex],
testI[searchStringIndex], comparison);
if (comparisonValue < 0)
{
resultString = "less than";
}
else if (comparisonValue > 0)
{
resultString = "greater than";
}
Console::WriteLine(resultFormat, testNames[testStringIndex], resultString,
testNames[searchStringIndex]);
}
int main()
{
String^ introMessage =
"Compare three versions of the letter I using different " +
"values of StringComparison.";
// Define an array of strings where each element contains a version of
// the letter I. (An array of strings is used so you can easily modify
// this code example to test additional or different combinations of
// strings.)
array<String^>^ letterVariation = gcnew array<String^>(3);
// LATIN SMALL LETTER I (U+0069)
letterVariation[0] = "i";
// LATIN SMALL LETTER DOTLESS I (U+0131)
letterVariation[1] = L"\u0131";
// LATIN CAPITAL LETTER I (U+0049)
letterVariation[2] = "I";
array<String^>^ unicodeNames = {
"LATIN SMALL LETTER I (U+0069)",
"LATIN SMALL LETTER DOTLESS I (U+0131)",
"LATIN CAPITAL LETTER I (U+0049)"};
array<StringComparison>^ comparisonValues = {
StringComparison::CurrentCulture,
StringComparison::CurrentCultureIgnoreCase,
StringComparison::InvariantCulture,
StringComparison::InvariantCultureIgnoreCase,
StringComparison::Ordinal,
StringComparison::OrdinalIgnoreCase};
Console::Clear();
Console::WriteLine(introMessage);
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
Console::WriteLine("The current culture is {0}.{1}",
Thread::CurrentThread->CurrentCulture->Name, Environment::NewLine);
// Determine the relative sort order of three versions of the letter I.
for each (StringComparison stringCmp in comparisonValues)
{
Console::WriteLine("StringComparison.{0}:", stringCmp);
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I
// (U+0131)
Test(0, 1, stringCmp, letterVariation, unicodeNames);
// LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, stringCmp, letterVariation, unicodeNames);
// LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I
// (U+0049)
Test(1, 2, stringCmp, letterVariation, unicodeNames);
Console::WriteLine();
}
}
/*
This code example produces the following results:
Compare three versions of the letter I using different values of
StringComparison.
The current culture is en-US.
StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER
DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN
CAPITAL LETTER I (U+0049)
*/
// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.
using System;
using System.Threading;
class Sample
{
public static void Main()
{
string intro = "Compare three versions of the letter I using different " +
"values of StringComparison.";
// Define an array of strings where each element contains a version of the
// letter I. (An array of strings is used so you can easily modify this
// code example to test additional or different combinations of strings.)
string[] threeIs = new string[3];
// LATIN SMALL LETTER I (U+0069)
threeIs[0] = "\u0069";
// LATIN SMALL LETTER DOTLESS I (U+0131)
threeIs[1] = "\u0131";
// LATIN CAPITAL LETTER I (U+0049)
threeIs[2] = "\u0049";
string[] unicodeNames =
{
"LATIN SMALL LETTER I (U+0069)",
"LATIN SMALL LETTER DOTLESS I (U+0131)",
"LATIN CAPITAL LETTER I (U+0049)"
};
StringComparison[] scValues =
{
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase
};
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
Console.WriteLine(
"The current culture is {0}.\n", Thread.CurrentThread.CurrentCulture.Name);
// Determine the relative sort order of three versions of the letter I.
foreach (StringComparison sc in scValues)
{
Console.WriteLine("StringComparison.{0}:", sc);
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
Test(0, 1, sc, threeIs, unicodeNames);
// LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, sc, threeIs, unicodeNames);
// LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
Test(1, 2, sc, threeIs, unicodeNames);
Console.WriteLine();
}
}
protected static void Test(
int x, int y, StringComparison comparison, string[] testI, string[] testNames)
{
string resultFmt = "{0} is {1} {2}";
string result = "equal to";
int cmpValue = 0;
cmpValue = String.Compare(testI[x], testI[y], comparison);
if (cmpValue < 0)
result = "less than";
else if (cmpValue > 0)
result = "greater than";
Console.WriteLine(resultFmt, testNames[x], result, testNames[y]);
}
}
/*
This code example produces the following results:
Compare three versions of the letter I using different values of StringComparison.
The current culture is en-US.
StringComparison.CurrentCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.CurrentCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.InvariantCultureIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.OrdinalIgnoreCase:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
*/
' This example demonstrates the
' System.String.Compare(String, String, StringComparison) method.
Imports System.Threading
Class Sample
Public Shared Sub Main()
Dim intro As String = "Compare three versions of the letter I using different " & _
"values of StringComparison."
' Define an array of strings where each element contains a version of the
' letter I. (An array of strings is used so you can easily modify this
' code example to test additional or different combinations of strings.)
Dim threeIs(2) As String
' LATIN SMALL LETTER I (U+0069)
threeIs(0) = "i"
' LATIN SMALL LETTER DOTLESS I (U+0131)
threeIs(1) = "ı"
' LATIN CAPITAL LETTER I (U+0049)
threeIs(2) = "I"
Dim unicodeNames As String() = { _
"LATIN SMALL LETTER I (U+0069)", _
"LATIN SMALL LETTER DOTLESS I (U+0131)", _
"LATIN CAPITAL LETTER I (U+0049)" }
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
'
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because the culture-specific comparisons
' can produce different results with different cultures.
Console.WriteLine("The current culture is {0}." & vbCrLf, _
Thread.CurrentThread.CurrentCulture.Name)
' Determine the relative sort order of three versions of the letter I.
Dim sc As StringComparison
For Each sc In scValues
Console.WriteLine("StringComparison.{0}:", sc)
' LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
Test(0, 1, sc, threeIs, unicodeNames)
' LATIN SMALL LETTER I (U+0069) : LATIN CAPITAL LETTER I (U+0049)
Test(0, 2, sc, threeIs, unicodeNames)
' LATIN SMALL LETTER DOTLESS I (U+0131) : LATIN CAPITAL LETTER I (U+0049)
Test(1, 2, sc, threeIs, unicodeNames)
Console.WriteLine()
Next sc
End Sub
Protected Shared Sub Test(ByVal x As Integer, ByVal y As Integer, _
ByVal comparison As StringComparison, _
ByVal testI() As String, ByVal testNames() As String)
Dim resultFmt As String = "{0} is {1} {2}"
Dim result As String = "equal to"
Dim cmpValue As Integer = 0
'
cmpValue = String.Compare(testI(x), testI(y), comparison)
If cmpValue < 0 Then
result = "less than"
ElseIf cmpValue > 0 Then
result = "greater than"
End If
Console.WriteLine(resultFmt, testNames(x), result, testNames(y))
End Sub
End Class
'
'This code example produces the following results:
'
'Compare three versions of the letter I using different values of StringComparison.
'The current culture is en-US.
'
'StringComparison.CurrentCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.CurrentCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCulture:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.InvariantCultureIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.Ordinal:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
'StringComparison.OrdinalIgnoreCase:
'LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
'LATIN SMALL LETTER I (U+0069) is equal to LATIN CAPITAL LETTER I (U+0049)
'LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
'
설명
comparisonType매개 변수는 비교 시 현재 또는 고정 문화권이 사용되어야 하는지, 비교된 문화권의 대/소문자를 인식하거나 무시해야 하는지 또는 단어(문화권 구분) 또는 서수(문화권 구분 안 함) 정렬 규칙을 사용해야 하는지 여부를 나타냅니다.
하나 또는 두 비교는 일 수 null 있습니다. 정의에 따라 빈 문자열("")을 포함한 모든 문자열은 null 참조보다 큰 문자열을 비교합니다. 두 null 참조는 서로 비교됩니다.
다른 문자열이 검색되거나 두 문자열을 모두 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다. 반환 값은 수행된 마지막 비교의 결과입니다.
문화권별 대/소문자 구분 규칙의 영향을 받는 비교 시 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 다음 예제에서는 터키어의 파일 시스템이 "file"의 문자 "i"에 대해 언어 대/소문자 규칙을 사용하지 않기 때문에 잘못된 결과를 산출합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서수 비교를 사용하여 경로 이름을 "file"과 비교합니다. 이 작업을 수행하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, String, StringComparison)메서드는 문화권 구분 비교를 수행할 때 이러한 문자를 고려하지 않습니다. 비교에서 무시 가능한 문자를 인식하려면 매개 변수에 대해 또는 값을 Ordinal 입력합니다. OrdinalIgnoreCase comparisonType
추가 정보
적용 대상
Compare(String, String, Boolean)
대/소문자를 구분하거나 구분하지 않고 지정된 두 String 개체를 비교하여 정렬 순서에서 두 개체의 상대 위치를 나타내는 정수를 반환합니다.
public:
static int Compare(System::String ^ strA, System::String ^ strB, bool ignoreCase);
public static int Compare (string strA, string strB, bool ignoreCase);
public static int Compare (string? strA, string? strB, bool ignoreCase);
static member Compare : string * string * bool -> int
Public Shared Function Compare (strA As String, strB As String, ignoreCase As Boolean) As Integer
매개 변수
- strA
- String
비교할 첫째 문자열입니다.
- strB
- String
비교할 둘째 문자열입니다.
- ignoreCase
- Boolean
비교 시 대/소문자를 무시하려면 true이고, 그러지 않으면 false입니다.
반환
두 비교 대상 간의 어휘 관계를 나타내는 32비트 부호 있는 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA 가 정렬 순서에서 strB 앞에 오는 경우
|
| 0 | strA가 정렬 순서에서 strB와 동일한 위치에서 발생합니다.
|
| 0보다 큼 | strA가 정렬 순서에서 strB 뒤에 오는 경우
|
예제
다음 예제에서는 Compare(String, String, Boolean) 메서드는 문자열을 비교할 때 또는 를 사용하는 것과 ToUpper ToLower 같습니다.
using namespace System;
void main()
{
// Create upper-case characters from their Unicode code units.
String^ stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String^ stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console::WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console::WriteLine("The Strings are equal when capitalized? {0}",
String::Compare(stringUpper->ToUpper(), stringLower->ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console::WriteLine("The Strings are equal when case is ignored? {0}",
String::Compare(stringUpper, stringLower, true) == 0
? "true" : "false");
}
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
String stringLower = "\x0061\x0062\x0063";
// Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower);
// Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
? "true" : "false");
// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
String.Compare(stringUpper, stringLower, true) == 0
? "true" : "false" );
// The example displays the following output:
// Comparing 'ABC' and 'abc':
// The Strings are equal when capitalized? true
// The Strings are equal when case is ignored? true
Public Module Example
Public Sub Main()
' Create upper-case characters from their Unicode code units.
Dim stringUpper As String = ChrW(&H41) + ChrW(&H42) + ChrW(&H43)
' Create lower-case characters from their Unicode code units.
Dim stringLower As String = ChrW(&H61) + ChrW(&H62) + ChrW(&H63)
' Display the strings.
Console.WriteLine("Comparing '{0}' and '{1}':",
stringUpper, stringLower)
' Compare the uppercased strings; the result is true.
Console.WriteLine("The Strings are equal when capitalized? {0}",
If(String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) = 0,
"true", "false"))
' The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
If(String.Compare(stringUpper, stringLower, true) = 0,
"true", "false"))
End Sub
End Module
' The example displays the following output:
' Comparing 'ABC' and 'abc':
' The Strings are equal when capitalized? true
' The Strings are equal when case is ignored? true
설명
비교에서는 현재 문화권을 사용하여 대/소문자 구분 규칙 및 개별 문자의 사전순과 같은 문화권별 정보를 얻습니다. 예를 들어 문화권은 특정 문자 조합을 단일 문자로 처리하거나 대문자와 소문자를 특정 방식으로 비교하도록 지정하거나 문자의 정렬 순서가 앞이나 뒤에 오는 문자에 따라 달라지도록 지정할 수 있습니다.
비교는 단어 정렬 규칙을 사용하여 수행됩니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 를 System.Globalization.CompareOptions 참조하세요.
경고
문자열을 비교할 때 메서드를 호출해야 합니다. 이 Compare(String, String, StringComparison) 경우 메서드에서 사용하는 문자열 비교 형식을 명시적으로 지정해야 합니다. 자세한 내용은 문자열 사용에 대한 모범 사례를 참조하세요.
하나 또는 두 비교는 일 수 null 있습니다. 정의에 따라 빈 문자열("")을 포함한 모든 문자열은 null 참조보다 큰 문자열을 비교합니다. 두 null 참조는 서로 비교됩니다.
다른 문자열이 검색되거나 두 문자열을 모두 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다. 반환 값은 수행된 마지막 비교의 결과입니다.
문화권별 대/소문자 구분 규칙의 영향을 받는 비교 시 예기치 않은 결과가 발생할 수 있습니다. 예를 들어 터키어에서 다음 예제에서는 터키어의 파일 시스템이 "file"의 문자 "i"에 대해 언어 대/소문자 규칙을 사용하지 않기 때문에 잘못된 결과를 산출합니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, true) == 0);
}
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
서수 비교를 사용하여 경로 이름을 "file"과 비교합니다. 이 작업을 수행하는 올바른 코드는 다음과 같습니다.
static bool IsFileURI(String^ path)
{
return (String::Compare(path, 0, "file:", 0, 5, StringComparison::OrdinalIgnoreCase) == 0);
}
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
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함됩니다. Compare(String, String, Boolean)메서드는 문화권 구분 비교를 수행할 때 이러한 문자를 고려하지 않습니다. 예를 들어 다음 코드가 .NET Framework 4 이상에서 실행되는 경우 "Ani-mal"(소프트 하이픈 또는 U+00AD 사용)과 "동물"의 문화권 구분 대/소문자를 구분하지 않는 비교는 두 문자열이 동일함을 나타냅니다.
문자열 비교에서 무시 가능한 문자를 인식하려면 Compare(String, String, StringComparison) 메서드를 호출하고 매개 변수에 대해 또는 값을 Ordinal 입력합니다. OrdinalIgnoreCase comparisonType
추가 정보
적용 대상
Compare(String, String, CultureInfo, CompareOptions)
지정된 두 String 개체를 비교하고 정렬 순서에서 두 문자열 간의 관계를 나타내는 정수를 반환합니다. 지정된 비교 옵션 및 문화권별 정보가 비교에 영향을 줍니다.
public:
static int Compare(System::String ^ strA, System::String ^ strB, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare (string? strA, string? strB, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare (string strA, string strB, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * string * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare (strA As String, strB As String, culture As CultureInfo, options As CompareOptions) As Integer
매개 변수
- strA
- String
비교할 첫째 문자열입니다.
- strB
- String
비교할 둘째 문자열입니다.
- culture
- CultureInfo
문화권별 비교 정보를 제공하는 문화권입니다. culture가 null이면 현재 문화권이 사용됩니다.
- options
- CompareOptions
대/소문자 또는 기호 무시 여부와 같이 비교를 수행할 때 사용할 옵션입니다.
반환
다음 표와 같이 strA와 strB 간의 어휘 관계를 나타내는 부호 있는 32비트 정수입니다.
| 값 | 조건 |
|---|---|
| 0보다 작음 | strA 가 정렬 순서에서 strB 앞에 오는 경우
|
| 0 | strA가 정렬 순서에서 strB와 동일한 위치에서 발생합니다.
|
| 0보다 큼 | strA가 정렬 순서에서 strB 뒤에 오는 경우
|
예외
options이 CompareOptions 값이 아닙니다.
예제
다음 예제에서는 세 가지 방법으로 두 문자열을 비교합니다. en-US 문화권에 대해 언어 비교를 사용합니다. en-US 문화권에 대/소문자를 구분하는 언어 비교 사용 서수 비교를 사용하는 및 입니다. 이 예제에서는 세 가지 비교 방법을 통해 세 가지 다른 결과를 생성하는 방법을 보여 줍니다.
using namespace System;
using namespace System::Globalization;
public ref class Example
{
public:
static void Main()
{
String^ string1 = "brother";
String^ string2 = "Brother";
String^ relation;
int result;
// Cultural (linguistic) comparison.
result = String::Compare(string1, string2, gcnew CultureInfo("en-US"),
CompareOptions::None);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console::WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Cultural (linguistic) case-insensitive comparison.
result = String::Compare(string1, string2, gcnew CultureInfo("en-US"),
CompareOptions::IgnoreCase);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console::WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Culture-insensitive ordinal comparison.
result = String::CompareOrdinal(string1, string2);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console::WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
}
};
int main()
{
Example::Main();
}
// The example produces the following output:
// 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string string1 = "brother";
string string2 = "Brother";
string relation;
int result;
// Cultural (linguistic) comparison.
result = String.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.None);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Cultural (linguistic) case-insensitive comparison.
result = String.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.IgnoreCase);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// Culture-insensitive ordinal comparison.
result = String.CompareOrdinal(string1, string2);
if (result > 0)
relation = "comes after";
else if (result == 0)
relation = "is the same as";
else
relation = "comes before";
Console.WriteLine("'{0}' {1} '{2}'.",
string1, relation, string2);
// The example produces the following output:
// 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
}
}
Imports System.Globalization
Public Module Example
Public Sub Main()
Dim string1 As String = "brother"
Dim string2 As String = "Brother"
Dim relation As String
Dim result As Integer
' Cultural (linguistic) comparison.
result = String.Compare(string1, string2, _
New CultureInfo("en-US"), CompareOptions.None)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
' Cultural (linguistic) case-insensitive comparison.
result = String.Compare(string1, string2, _
New CultureInfo("en-US"), CompareOptions.IgnoreCase)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
' Culture-insensitive ordinal comparison.
result = String.CompareOrdinal(string1, string2)
If result > 0 Then
relation = "comes after"
ElseIf result = 0 Then
relation = "is the same as"
Else
relation = "comes before"
End If
Console.WriteLine("'{0}' {1} '{2}'.", string1, relation, string2)
End Sub
End Module
' The example produces the following output:
' 'brother' comes before 'Brother'.
' 'brother' is the same as 'Brother'.
' 'brother' comes after 'Brother'.
설명
비교에서는 매개 변수를 사용하여 culture 대/소문자 구분 규칙 및 개별 문자의 사전순과 같은 문화권별 정보를 얻습니다. 예를 들어 특정 문화권은 특정 문자 조합을 단일 문자로 처리하거나, 대문자와 소문자를 특정 방식으로 비교하거나, 문자의 정렬 순서가 앞이나 뒤에 오는 문자에 따라 달라지도록 지정할 수 있습니다.
주의
Compare(String, String, CultureInfo, CompareOptions)메서드는 주로 정렬 또는 사전순 작업에 사용하도록 설계되었습니다. 메서드 호출의 기본 목적이 두 문자열이 동일한지 여부를 확인하는 경우(즉, 메서드 호출의 목적이 반환 값 0을 테스트하는 것일 때) 사용하면 안 됩니다. 두 문자열이 동일한지 여부를 확인하려면 Equals 메서드를 호출합니다.
비교는 options 하나 이상의 열거형 멤버로 구성되는 매개 변수를 통해 추가로 지정할 수 CompareOptions 있습니다. 그러나 이 메서드의 목적은 문화권 구분 문자열 비교를 수행하는 것이므로 CompareOptions.Ordinal 및 CompareOptions.OrdinalIgnoreCase 값은 영향을 미치지 않습니다.
비교 또는 둘 다 일 수 null 있습니다. 정의에 따라 를 포함한 모든 String.Empty 문자열은 null 참조보다 큰 것을 비교하고 두 null 참조는 서로 비교됩니다.
다른 문자열이 검색되거나 두 문자열을 모두 비교하면 비교가 종료됩니다. 그러나 두 문자열이 한 문자열의 끝과 비교되고 다른 문자열에 남은 문자가 있는 경우 나머지 문자가 있는 문자열은 더 큰 것으로 간주됩니다.
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함되며, 이들 문자는 언어 또는 문화권 구분 비교를 수행하는 경우 고려되지 않습니다. Compare(String, String, CultureInfo, CompareOptions)메서드는 문화권 구분 비교를 수행할 때 이러한 문자를 고려하지 않습니다. 비교에서 무시 가능한 문자를 인식하려면 매개 변수에 대해 또는 값을 Ordinal 입력합니다. OrdinalIgnoreCase options