IT박스

C # 대소 문자를 구분하지 않는 equals 연산자가 있습니까?

itboxs 2020. 6. 13. 19:29
반응형

C # 대소 문자를 구분하지 않는 equals 연산자가 있습니까?


다음은 대소 문자를 구분한다는 것을 알고 있습니다.

if (StringA == StringB) {

그래서 두 문자열을 둔감하게 비교하는 연산자가 있습니까?


이 시도:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

대소 문자를 무시하고 두 문자열을 비교 하는 가장 좋은 방법String.Equals 정적 메서드를 사용하여 서수 무시 문자열 비교를 지정하는 것입니다. 또한 문자열을 소문자 나 대문자로 변환 한 후 비교하는 것보다 훨씬 빠른 방법입니다.

두 가지 접근 방식의 성능을 테스트했으며 서수 무시 문자열 비교가 9 배 이상 빨랐습니다 ! 문자열을 소문자 또는 대문자로 변환하는 것보다 안정적입니다 (터키어 i 문제를 확인하십시오). 따라서 항상 String.Equals 메소드를 사용하여 문자열이 동일한 지 비교하십시오.

String.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

문화권 별 문자열 비교를 수행하려는 경우 다음 코드를 사용할 수 있습니다.

String.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);

두 번째 예는 현재 문화권의 문자열 비교 논리를 사용하므로 첫 번째 예의 "단일 무시 무시"비교보다 느리므로 문화권 별 문자열 비교 논리가 필요하지 않은 경우 최대 성능을 발휘 한 후 "소수점 무시 무시"비교를 사용하십시오.

자세한 내용 은 내 블로그에서 전체 기사를 읽으십시오 .


StringComparer정적 클래스에는 원하는 모든 유형의 대 / 소문자 구분에 대한 비교자를 반환 하는 여러 속성 이 있습니다.

StringComparer 속성

예를 들어

StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)

또는

StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)

인수 를 취하는 과부하 string.Equals또는 string.Compare과부하 보다 약간 깨끗합니다 StringComparison.


System.Collections.CaseInsensitiveComparer

또는

System.StringComparer.OrdinalIgnoreCase

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

또는

if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {

그러나 StringA가 null이 아닌지 확인해야합니다. 따라서 아마도 더 나은 사용법입니다.

string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);

요한이 제안한대로

편집 : 버그 수정


당신이 사용할 수있는

if (stringA.equals(StringB, StringComparison.CurrentCultureIgnoreCase))

구문을 단순화하는 아이디어는 다음과 같습니다.

public class IgnoreCase
{
    private readonly string _value;

    public IgnoreCase(string s)
    {
        _value = s;
    }

    protected bool Equals(IgnoreCase other)
    {
        return this == other;
    }

    public override bool Equals(object obj)
    {
        return obj != null &&
               (ReferenceEquals(this, obj) || (obj.GetType() == GetType() && this == (IgnoreCase) obj));
    }

    public override int GetHashCode()
    {
        return _value?.GetHashCode() ?? 0;
    }

    public static bool operator ==(IgnoreCase a, IgnoreCase b)
    {
        return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
    }

    public static bool operator !=(IgnoreCase a, IgnoreCase b)
    {
        return !(a == b);
    }

    public static implicit operator string(IgnoreCase s)
    {
        return s._value;
    }

    public static implicit operator IgnoreCase(string s)
    {
        return new IgnoreCase(s);
    }
}

다음과 같이 사용 가능 :

Console.WriteLine((IgnoreCase) "a" == "b"); // false
Console.WriteLine((IgnoreCase) "abc" == "abC"); // true
Console.WriteLine((IgnoreCase) "Abc" == "aBc"); // true
Console.WriteLine((IgnoreCase) "ABC" == "ABC"); // true

운영자? 아니요, 그러나 문자열 비교가 대소 문자를 구분하지 않도록 문화를 변경할 수 있다고 생각합니다.

// you'll want to change this...
System.Threading.Thread.CurrentThread.CurrentCulture
// and you'll want to custimize this
System.Globalization.CultureInfo.CompareInfo

equals 연산자로 문자열을 비교하는 방식이 변경 될 것이라고 확신합니다.


이 비교 방법의 끝에 입력하는 데 익숙합니다. , StringComparison.

그래서 확장했습니다.

namespace System
{   public static class StringExtension
    {
        public static bool Equals(this string thisString, string compareString,
             StringComparison stringComparison)
        {
            return string.Equals(thisString, compareString, stringComparison);
        }
    }
}

Just note that you will need to check for null on thisString prior to calling the ext.


string.Compare(string1, string2, true)

if (StringA.ToUpperInvariant() == StringB.ToUpperInvariant()) {

People report ToUpperInvariant() is faster than ToLowerInvariant().


Others answer are totally valid here, but somehow it takes some time to type StringComparison.OrdinalIgnoreCase and also using String.Compare.

I've coded simple String extension method, where you could specify if comparison is case sensitive or case senseless with boolean - see following answer:

https://stackoverflow.com/a/49208128/2338477


Just do

if (stringA.toLower() == stringB) {};

Then write StringB as a lowercase, to do stringB.toLower() as well.

.toLower() returns a copy of the string as lowercase and therefore will not alter the original string.

참고URL : https://stackoverflow.com/questions/631233/is-there-a-c-sharp-case-insensitive-equals-operator

반응형