Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

리눅스 환경의 .NET Core에서 "test".IndexOf("\0")가 0을 반환

희한하군요. 다음의 코드가 윈도우와 리눅스에서 결과가 다릅니다.

string txt = "test";
Console.WriteLine(txt.IndexOf("\0")); // 윈도우 환경: -1 반환
                                      // 리눅스 환경: 0 반환

심지어 다음과 같이 해도 마찬가지입니다.

string txt = "test\0\0test";
Console.WriteLine(txt.IndexOf("\0")); // 윈도우에서는 4 반환
                                      // 리눅스에서는 0 반환




검색해 보면 다음의 글이 나오는데,

What happens when you IndexOf an empty string?
; https://dev.to/turnerj/what-happens-when-you-indexof-an-empty-string-1m0c

빈 문자열의 경우에는 윈도우와 리눅스 환경에서 동일하게 0을 반환합니다.

string txt = "test";
Console.WriteLine(txt.IndexOf("")); // 윈도우 및 리눅스 환경: 0 반환

null 문자와는 다르게, 사실 빈 문자열에 대해서는 어떤 값이 반환되어야 할 지 판단 기준이 잘 안 서는데요, 이에 대해 MSDN 문서에 설명이 있습니다.

Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. If value consists only of one or more ignorable characters, the IndexOf(String, Int32, Int32) method always returns startIndex, which is the character position at which the search begins.


위의 이야기에 따르면 "ignorable characters"에 포함하는 문자를 IndexOf로 찾는 경우에는 startIndex의 값을 반환한다고 합니다. 실제로 테스트 결과 그렇게 나옵니다.

Console.WriteLine(txt.IndexOf("\0")); // 0 반환

Console.WriteLine(txt.IndexOf("\0", 2)); // 2 반환

정리해 보면, 빈 문자열과 '\0' 널 문자는 리눅스 환경에서는 "ignorable characters"에 속하고, 윈도우 환경에서는 빈 문자열만 해당하는 것입니다.




참고로 "What happens when you IndexOf an empty string?" 글에서 인용한 내용을 보면 힌트가 하나 더 있습니다.

Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. If value consists only of one or more ignorable characters, the IndexOf(String) method always returns 0 (zero) to indicate that the match is found at the beginning of the current instance.


따라서 리눅스에서도 StringComparison의 옵션에 따라 결과가 달라집니다.

Console.WriteLine(txt.IndexOf("\0", StringComparison.Ordinal)); // -1 반환
Console.WriteLine(txt.IndexOf("\0", StringComparison.OrdinalIgnoreCase)); // -1 반환
Console.WriteLine(txt.IndexOf("\0", StringComparison.InvariantCulture)); // 0 반환
Console.WriteLine(txt.IndexOf("\0", StringComparison.CurrentCultureIgnoreCase)); // 0 반환
Console.WriteLine(txt.IndexOf("\0", StringComparison.InvariantCultureIgnoreCase)); // 0 반환

문서에서 언급한 것처럼 "Ordinal or OrdinalIgnoreCase" 상황에서는 저렇게 -1을 정상적으로 반환합니다.

마지막으로 다음의 결과도 인상적입니다.
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string result = null;

            result = "\r\n";

            // Environment.NewLine == A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
            int pos = result.IndexOf(Environment.NewLine);
            Console.WriteLine(pos); // -1

            pos = result.IndexOf(Environment.NewLine, 0, StringComparison.OrdinalIgnoreCase);
            Console.WriteLine(pos); // 1

            result = Environment.NewLine;
            pos = result.IndexOf(Environment.NewLine);
            Console.WriteLine(pos); // 0

            result = "test\n";
            pos = result.IndexOf(Environment.NewLine);
            Console.WriteLine(pos); // 4

            result = "test\r\n";
            pos = result.IndexOf(Environment.NewLine);
            Console.WriteLine(pos); // -1
        }
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/8/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...
NoWriterDateCnt.TitleFile(s)
586정성태6/4/200826105오류 유형: 56. WPF 디자이너 - The string was not recognized as a valid DateTime [2]
585정성태6/4/200834340.NET Framework: 101. WPF - ActiveX 컨트롤 호스팅하는 방법 [2]
582정성태5/16/200826131오류 유형: 55. Windowless ActiveX controls are not supported
580정성태4/24/200825241VC++: 34. 64비트 윈도우즈에서의 이벤트 후킹
579정성태4/24/200825022VC++: 33. 변환 후의 RGS 파일 내용을 얻는 방법
577정성태4/16/200826001.NET Framework: 100. XML Serializer를 이용한 값 복사 [5]
575정성태4/7/200823205오류 유형: 54. TFS Source Control - 명령을 사용할 수 없음 [2]
574정성태3/31/200821354오류 유형: 53. TFS 연결 오류 - The workspace [...] exists on computer [...]
573정성태3/25/200825353Windows: 31. TS Web Access와 UAC [1]
570정성태3/17/200824472오류 유형: 52. TFS 연결 오류 - TF31001 [2]
569정성태3/16/200825582Team Foundation Server: 24. TFS 2008로 마이그레이션 (2) [2]
566정성태2/28/200826716.NET Framework: 99. AppDomain.GetEntryAssembly()를 우회하는 방법파일 다운로드1
564정성태2/16/200826404Windows: 30. TS Web Access + Vista SP1 [2]
563정성태2/16/200825753오류 유형: 51. Vista(UAC) + 웹 프로젝트 디버깅: System.UnauthorizedAccessException
562정성태2/12/200830014Windows: 29. Windows Server 2008 설치 [4]
561정성태1/10/200823676오류 유형: 50. IE 7 + 잘못된 HTC 파일 경로 = File not found [5]
559정성태1/1/200828483Windows: 28. Vista에서 끌어다 놓기로 GAC 등록하는 방법 [2]
558정성태1/1/200845626개발 환경 구성: 33. 32bit/64bit OLE DB Provider [1]
557정성태12/22/200723945개발 환경 구성: 32. WSCF와 VS.NET 2008
556정성태12/16/200722108기타: 22. 인기 순위 정리 : 조회수 1000 회 이상
555정성태12/16/200725050기타: 21. 인기 순위 정리 : 조회수 500 ~ 999회 글 목록
554정성태12/16/200729543기타: 20. 인기 순위 정리 : 조회수 250 ~ 499회 글 목록
553정성태12/16/200729937기타: 19. 인기 순위 정리 : 조회수 100 ~ 249회 글 목록
552정성태12/16/200723508기타: 18. 인기 순위 정리 : 조회수 000 ~ 099 회 글 목록
550정성태12/16/200722630Team Foundation Server: 23. TFS 2005에서 TFS 2008로 마이그레이션 [2]
549정성태12/16/200723981Team Foundation Server: 22. TFS 설정 - 주소를 도메인으로 변경
... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...