program tip

"abcd".StartsWith ( "")가 true를 반환하는 이유는 무엇입니까?

radiobox 2020. 9. 20. 09:23
반응형

"abcd".StartsWith ( "")가 true를 반환하는 이유는 무엇입니까?


제목은 전체 질문입니다. 누군가가 이런 일이 발생하는 이유를 알려줄 수 있습니까?


예-빈 문자열로 시작하기 때문입니다. 실제로 빈 문자열은 모든 문자 쌍 사이에 논리적으로 발생합니다.

이렇게 말하면 "시작"의 어떤 정의가이를 배제 할 수 있습니까? 다음은 그렇지 않은 "시작"에 대한 간단한 정의입니다.

"x의 첫 y.Length문자 가 y의 문자와 일치 하면 x는 y로 시작합니다 ."

대체 (동등한) 정의 :

"x는 y로 시작하면 x.Substring(0, y.Length).Equals(y)"


나는 Jon Skeet가 말한 것에 대해 자세히 설명하려고 노력할 것입니다.

x, y 및 z가 문자열이고 + 연산자가 실제로 연결이라고 가정 해 보겠습니다.

z를 분할하여 z = x + y를 쓸 수 있다면 z가 x로 시작 함을 의미합니다. 모든 문자열 z는 z = ""+ z로 분할 될 수 있으므로 모든 문자열이 ""로 시작합니다.

따라서 ( ""+ "abcd") == "abcd"이므로 "abcd"는 ""로 시작합니다.


이 메서드는 value 매개 변수를 value와 길이가 같은이 문자열의 시작 부분에있는 하위 문자열과 비교하여 같은지 여부를 나타내는 값을 반환합니다. 동일하려면 값이 빈 문자열 (Empty)이거나 동일한 인스턴스에 대한 참조이거나이 인스턴스의 시작과 일치해야합니다.

.NET String.StartsWith

인수가 나타내는 문자 시퀀스가이 문자열이 나타내는 문자 시퀀스의 접두사이면 true이고; 그렇지 않으면 거짓. 또한 인수가 빈 문자열 이거나 equals (Object) 메서드에 의해 결정된이 String 객체와 같은 경우 true가 반환됩니다 .

자바 String.startsWith


이해하기 쉬운 관련 사실부터 시작하겠습니다.

빈 집합은 모든 집합의 하위 집합입니다.

왜? 정의서브 세트 상태 A의 부분 집합 B의 모든 요소가있는 경우 A의 원소이다 B. 반대로 의 요소 가 아닌 요소가있는 경우 A의 하위 집합 이 아닙니다 .BAB

이제 세트를 수정하십시오 B. 빈 집합이 B. 빈 집합이의 하위 집합이 아닌 경우가 아님을 보여줌으로써이를 수행합니다 B. 빈 집합이의 하위 집합이 아니면에없는 빈 집합 B의 요소를 찾을 수 B있습니다. 그러나 빈 집합에는 요소가 없으므로 .NET에없는 요소를 찾을 수 없습니다 B. 따라서 빈 집합이의 하위 집합이 아닌 것은 아닙니다 B. 따라서 빈 집합은의 하위 집합이어야합니다 B.

모든 문자열은 빈 문자열로 시작합니다.

먼저, 시작 에 대한 정의에 동의해야합니다 . Let sand tbe strings 우리는 if로 s 시작 하고의 첫 문자 . 즉, 모든에 대한 그와 같은 , 사실이다. 반대로 if 문으로 시작하지 않는다고 말할 수 있습니다 .ts.Length >= t.Lengtht.Lengthtss.Length >= t.LengthInt32 index0 <= index < t.Lengths[index] == t[index]st

s.Length < t.Length또는 s.Length >= t.Length거기있는 Int32 index그러한 0 <= index < t.Lengths[index] != t[index]

사실이다. 일반 영어에서는 s보다 짧 t거나, 그렇지 않은 경우 t에서 동일한 위치와 일치하지 않는 문자가 s있습니다.

이제 문자열을 수정합니다 s. s빈 문자열로 시작하도록 설정하겠습니다 . s빈 문자열로 시작하지 않는 경우가 아니라는 것을 보여 주면서이를 수행하겠습니다 . 경우 s다음 빈 문자열로 시작하지 않는 s.Length < String.Empty.Length또는 s.Length >= String.Empty.Length과가 Int32 index그 같은 0 <= index < String.Empty.Length. 그러나 s.Length >= 0그리고 String.Empty.Length0과 같으므로 사실이 s.Length < String.Empty.Length될 수 없습니다 . 마찬가지로``String.Empty.Length is equal to zero, there is noInt32 index satisfying0 <= index <String.Empty.Length`. 따라서

s.Length < String.Empty.Length또는 s.Length >= String.Empty.Length및가 Int32 index되도록0 <= index < String.Empty.Length

거짓입니다. 따라서 s빈 문자열로 시작하지 않는 경우 가 아닙니다. 따라서 s빈 문자열로 시작해야합니다.

다음은 의 확장으로 코딩 된 시작 의 구현입니다 string.

public static bool DoStartsWith(this string s, string t) {
    if (s.Length >= t.Length) {
        for (int index = 0; index < t.Length; index++) {
            if (s[index] != t[index]) {
                return false;
            }
        }
        return true;
    }
    return false;
}

위의 두 가지 대담한 사실은 막연하게 진실 된 진술의 예입니다 . 그것들을 정의하는 문 ( 부분 집합과시작 )이 빈 우주에 대한 보편적 인 정량화 라는 사실 때문에 사실입니다 . 빈 세트에는 요소가 없으므로 다른 고정 세트가 아닌 빈 세트의 요소가있을 수 없습니다. 빈 문자열에는 문자가 없으므로 다른 고정 문자열의 동일한 위치에있는 문자와 일치하지 않는 빈 문자열의 일부 위치로 문자가있을 수 없습니다.


그냥 "abcd".StartsWith("")return false 라고합시다 .

if so then what does the following expression eval to, true or false:

 ("abcd".Substring(0,0) == "")

it turns out that evals to true, so the string does start with the empty string ;-), or put in other words, the substring of "abcd" starting at position 0 and having 0 length equals the empty string "". Pretty logical imo.


In C# this is how the specification tells it to react;

To be equal, value must be an empty string (Empty), a reference to this same instance, or match the beginning of this instance.


The first N characters of the two strings are identical. N being the length of the second string, i.e. zero.


Why does “abcd”.StartsWith(“”) return true?

THE REAL ANSWER:

It has to be that way otherwise you'd have the case where

    "".startsWith("") == false 
    "".equals("") == true

    but yet

    "a".startsWith("a") == true
    "a".equals("a") == true

and then we'd have Y2K all over again because all the bank software that depends on equal strings starting with themselves will get our accounts mixed up and suddenly Bill Gates will have my wealth and I'd have his, and damn it! Fate just isn't that kind to me.


Just for the record, String.StartsWith() internally calls the method System.Globalization.CultureInfo.IsPrefix() which makes the following check explicitly:

if (prefix.Length == 0)
{
    return true;
}

Because a string begins well with "nothing".


If you think of it in regular expressions terms, it makes sense. Every string (not just "abcd", also "" and "sdf\nff") , returns true when evaluating the regular expression of 'starts with empty string'.


In C#, the reason it returns true is that the developers specifically coded for it.

If you check out the source code, you'll find specific logic to handle an empty string:

public Boolean StartsWith(String value)
{
    return StartsWith(value, StringComparison.CurrentCulture);
}

public Boolean StartsWith(String value, StringComparison comparisonType)
{
    ...

    if (value.Length == 0)
    {
        return true;
    }

참고URL : https://stackoverflow.com/questions/145509/why-does-abcd-startswith-return-true

반응형