Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 5개 있습니다.)
오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
; https://www.sysnet.pe.kr/2/0/13266

닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13430

C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows)
; https://www.sysnet.pe.kr/2/0/13796

C/C++: 185. C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점
; https://www.sysnet.pe.kr/2/0/13797

닷넷: 2308. C# - ICU 라이브러리를 활용한 문자열의 대소문자 변환
; https://www.sysnet.pe.kr/2/0/13800




C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점

(이 글에 포함된 일부 유니코드 문자는 모바일 웹 브라우저에서는 정상적으로 안 보일 수 있습니다.)




C++에서 문자열의 대소문자를 변환하는 방법을 검색해 보면 아래의 코드로 설명하는 답변들이 많습니다.

// tolower function for C++ strings
// https://stackoverflow.com/questions/3403844/tolower-function-for-c-strings

std::string str = "wHatEver";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);

그런데, 저 코드가 지닌 문제점을 아래의 글에서 아주 잘 설명하고 있습니다.

A popular but wrong way to convert a string to uppercase or lowercase
; https://devblogs.microsoft.com/oldnewthing/20241007-00/?p=110345

간단하게 정리해 볼까요? ^^

우선, tolower 함수는 "addressible function"이 아닙니다. 따라서, 엄밀히는 람다를 이용해 다음과 같이 바꿔야 합니다.

std::wstring name;

std::transform(name.begin(), name.end(), name.begin(),
    [](auto c) { return std::tolower(c); });

하지만 그래도 문제가 있습니다. 위에서 tolower는 unsigned char 타입을 처리하는, 즉 narrow characters를 처리하는 함수입니다.

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\convert\tolower_toupper.cpp
extern "C" int __cdecl tolower(int const c)
{
    return __acrt_locale_changed()
        ? _tolower_l(c, nullptr)
        : __ascii_tolower(c);
}

__forceinline int __CRTDECL __ascii_tolower(int const _C)
{
    if (_C >= 'A' && _C <= 'Z')
    {
        return _C - ('A' - 'a');
    }
    return _C;
}

따라서 wchar_t 타입(wide characters)을 처리하는 경우에는 towlower 함수를 사용해야 맞습니다.

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\convert\towlower.cpp
extern "C" wint_t __cdecl towlower (wint_t c)
{
    return _towlower_l(c, nullptr);
}

하지만, tolower를 사용해도 그런대로 잘 동작하는데요, 왜냐하면 tolower의 인자가 int 타입이라 wchar_t 타입을 받을 수 있고, 대부분의 경우 영문자 알파벳 'A' ~ 'Z'를 'a' ~ 'z'로 변환하는 것을 기대하기 때문입니다.




그런 탓에, 일단은 Visual C++에서 transform 코드에 사용하는 것은 크게 문제가 되진 않습니다.

하지만, tolower/towlower로는 진정한 유니코드 범위의 문자를 처리할 수 없습니다. 왜냐하면, 그 2가지 함수는 변환 자체를 하나의 char/wchar_t를 대상으로 하기 때문인데요, 이로 인해 Surrogate Pair를 처리할 수 없습니다.

"A popular but wrong way to convert a string to uppercase or lowercase"글에서는 이에 대한 사례로 U+10C80 코드(OLD HUNGARIAN CAPITAL LETTER)에 해당하는 '𐲀' 문자와 그것의 소문자에 해당하는 U+10CC0(OLD HUNGARIAN SMALL LETTER A) '𐳀' 문자를 들고 있습니다.

U+10C80 문자의 UTF-16 인코딩 값은 Surrogate Pair에 해당하는 "0xD803 0xDC80" 4바이트로 표현하는데요, 따라서 transform으로 변환하면 2바이트씩 별개로 처리돼 소문자 변환에 실패하게 됩니다.

#include <iostream>
#include <algorithm>

#include <fcntl.h>
#include <io.h>

int main(int, char* [])
{
    (void)_setmode(_fileno(stdout), _O_U16TEXT);

    std::wstring name = L"TEST한글𐲀";

    std::transform(name.begin(), name.end(), name.begin(),
        [](auto c) {
            wprintf(L"%c == %d (%x)\n", c, c, c);
            return towlower(c); 
        });

    std::wcout << name << std::endl;
}

/* 출력 결과
T == 84 (54)
E == 69 (45)
S == 83 (53)
T == 84 (54)
한 == 54620 (d55c)
글 == 44544 (ae00)
  == 55299 (d803)
  == 56448 (dc80)
test한글𐲀
*/

보는 바와 같이 '𐲀' 문자는 towlower 함수에 d803, dc80 두 개로 나뉘어 전달돼 정상적인 소문자 변환이 되지 않았습니다. 저 문제가 해결되려면 wchar_t가 4바이트로 다뤄져야 하는데요, 여기서 재미있는 건, ^^ 설령 그렇게 해도 여전히 문제가 되는 경우가 있다고 합니다. 특이하게도, 소문자일 때는 1개의 문자였던 것이 대문자로 바뀔 때는 2개의 문자로 바뀌는 경우라고 하는데요, 예를 들어 소문자인 U+00DF(ß) LATIN SMALL LETTER SHARP S 문자가 대문자로 바뀌는 경우에는 'S' 문자가 2개인 "SS"로 바뀌게 됩니다. 즉, "Straße" 문자열을 대문자로 바꾸면 "STRASSE"가 되어 버립니다.

유사하게 역시 소문자인 U+FB02(fl) LATIN SMALL LIGATURE FL은 대문자로 바뀌는 경우에는 "FL" 2개의 문자로 바뀌게 됩니다. 즉, 대소문자 변환 시 길이까지도 변하는 경우가 있는 것입니다.

또 다른 특이 사례로, 프랑스어에는 '소문자' + '악센트 문자' 2개의 글자가 (폰트로는) 1개의 '소문자 악센트 문자'로 표현되는 것도 있는데요, 이것을 대문자로 바꾸면 마찬가지로 '대문자' + '악센트 문자'로 바뀝니다.

소문자 'à' (\x0061\x0300) == 'a' U+0061 (Latin Small Letter A) + U+0300 (COMBINING GRAVE ACCENT)

대문자 'À' (\x0041\x0300) == 'A' U+0041 (Latin Capital Letter A) + U+0300 (COMBINING GRAVE ACCENT)

따라서, 16비트 값 하나로 그 문자의 대소문자를 결정할 수 없기 때문에 단순히 1:1 매핑으로 변환하려는 transform + tolower/towlower와 같은 방식은 이런 문제를 근본적으로 해결할 수 없는 것입니다.

그렇다면, 당연히 문맥을 고려할 수 있는 전용 함수가 있어야 하는데요, Windows의 경우 LCMapStringEx 함수가 그 용도로 사용할 수 있다고 합니다.

LCMapStringEx function (winnls.h)
; https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-lcmapstringex

그래서, 실제로 사용을 해봤는데요,

#include <iostream>
#include <algorithm>
#include <windows.h>

#include <fcntl.h>
#include <io.h>

int main(int, char* [])
{
    (void)_setmode(_fileno(stdout), _O_U16TEXT);

    LPCWSTR localeName = LOCALE_NAME_INVARIANT;
    // LPCWSTR localeName = L"hu-HU";

    {
        std::wstring name = L"TEST한글\xd803\xdc80";
        DWORD dwMapFlags = LCMAP_LOWERCASE | LCMAP_LINGUISTIC_CASING;

        int needBytes = LCMapStringEx(localeName, dwMapFlags,
            name.c_str(), -1, nullptr, 0, (LPNLSVERSIONINFO)&nvi, nullptr, 0);
        wchar_t* buffer = new wchar_t[needBytes];

        memset(buffer, 0, needBytes * sizeof(wchar_t));
        int result = LCMapStringEx(localeName, dwMapFlags,
            name.c_str(), (int)name.length(), buffer, needBytes, nullptr, nullptr, 0);

        std::wcout << name << std::endl;
        std::wcout << buffer << std::endl;
    }
    wprintf(L"\n");
}

/* 출력 결과:
TEST한글𐲀
test한글𐲀
*/

name과 buffer의 출력 결과를 보면, '𐲀' 문자가 소문자 U+10CC0(OLD HUNGARIAN SMALL LETTER A)로 변환되지 않았습니다.

혹시 함수에 전달한 옵션의 다른 조합이 있는 것일까요? ^^; 다른 예제가 있을까 싶어 검색해 봤더니, 마침 저처럼 "A popular but wrong way to convert a string to uppercase or lowercase"를 참조한 글이 있었습니다.

How To Convert Unicode Strings to Lower Case and Upper Case in C++
; https://giodicanio.com/2024/10/09/how-to-convert-unicode-strings-to-lower-case-and-upper-case-in-c-plus-plus/

또한, github에 관련 코드도 공개했길래,

GiovanniDicanio/StringCaseConversion
; https://github.com/GiovanniDicanio/StringCaseConversion/tree/main

반가워 살펴봤지만 ^^; 저랑 같은 코드였습니다. 단지, 그가 저 코드를 자신 있게 공개할 수 있었던 것은, ^^; 제가 했던 테스트를 하지 않았기 때문에 잘 동작한다고 믿었던 것 같습니다.

문제를 떠넘기는 ^^ 바람직한 자세로, 이슈를 넌지시 던져봤는데요,

It doesn't work in a context-free manner. #1
; https://github.com/GiovanniDicanio/StringCaseConversion/issues/1

stackoverflow에 있는 글을 링크하며 회피했습니다. ^^

Why does LCMapStringEx fail to convert OLD HUNGARIAN CAPITAL LETTER A (U+10C80) to lowercase?
; https://stackoverflow.com/questions/79142316/why-does-lcmapstringex-fail-to-convert-old-hungarian-capital-letter-a-u10c80

결국 제가 내린 결론은, 정작 Raymond Chen 자신도 LCMapStringEx 코드로는 테스트한 적이 없어서 저런 식의 글을 썼다는 ... 의심이 들었습니다.




그래도, Raymond Chen의 글에서 언급한 icu 라이브러리는,

If you need to perform a case mapping on a string, you can use LCMap­String­Ex with LCMAP_LOWERCASE or LCMAP_UPPERCASE, possibly with other flags like LCMAP_LINGUISTIC_CASING. If you use the International Components for Unicode (ICU) library, you can use u_strToUpper and u_strToLower.


잘 동작했고, 이에 대해서는 지난 글에 소개를 했습니다.

C++ - ICU dll을 이용하는 예제 코드 (Windows)
; https://www.sysnet.pe.kr/2/0/13796

위의 글에서는 소문자로의 변환만 테스트를 했었는데요, 대문자의 경우에도 다음과 같이 테스트를 작성해 보면,

wchar_t pText2[] = L"\x00DF, \x0061\x0300, \xFB02";
UChar* upperStr;

{
    uText = (UChar*)pText2;

    // 우선, 대문자로 변환했을 때의 결과물을 위해 필요한 버퍼 크기를 알아냄.
    length = u_strToUpper(NULL, 0, uText, -1, nullptr, &errorCode);

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    if (length < 1)
    {
        printf("Error: length less than 1.\n");
        return 1;
    }

    // UTF-16 (2바이트) 대문자 텍스트가 보관될 버퍼 할당
    upperStr = (UChar*)malloc((length + 1) * sizeof(UChar));

    if (!upperStr)
    {
        printf("Error: unable to allocate memory (3).\n");
        return 1;
    }
}

{
    retLength = u_strToUpper(upperStr, length + 1, uText, -1, nullptr, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(upperStr);
        return 1;
    }

    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), pText2, wcslen(pText2), NULL, NULL);
    printf(", len(lower_text): %zu\n", wcslen(pText2));

    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), upperStr, retLength, NULL, NULL);
    printf(", len(upper_text): %d\n", retLength);

    free(upperStr);
}

/* 출력 결과:
ß, à, fl, len(lower_text): 8
SS, À, FL, len(upper_text): 10
*/

보는 바와 같이 "A popular but wrong way to convert a string to uppercase or lowercase" 글에서 언급한 몇 가지 사례에 대해 정확하게 변환됐습니다.




어느 글에선가, wcslwr 함수를 사용하면 어떠냐는 글이 있었던 것 같은데요,

{
    wchar_t buffer[1024] = L"TEST한글𐳀𐲀";

    _locale_t loc = _create_locale(LC_ALL, "hu-HU");
    _wcslwr_s_l(buffer, wcslen(buffer) + 1, loc);
    std::wcout << buffer << std::endl;
}

결과는 LCMapStringEx와 동일합니다. 왜냐하면 wcslwr 함수는 내부적으로 LCMapStringEx를 호출하기 때문입니다.

// 반면 ReactOS의 경우 wcslwr 함수는 tolower 함수를 호출합니다.
// https://doxygen.reactos.org/d2/d20/wcslwr_8c_source.html
// https://doxygen.reactos.org/d3/d42/ctype_8c_source.html#l00901

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\string\wcslwr.cpp

static errno_t __cdecl _wcslwr_s_l_stat (
        _Inout_updates_z_(sizeInWords) wchar_t * wsrc,
        size_t sizeInWords,
        _locale_t plocinfo
        )
{

    // ...[생략]...

    /* Inquire size of wdst string */
    if ( (dstsize = __acrt_LCMapStringW(
                    plocinfo->locinfo->locale_name[LC_CTYPE],
                    LCMAP_LOWERCASE,
                    wsrc,
                    -1,
                    nullptr,
                    0
                    )) == 0 )
    {
        errno = EILSEQ;
        return errno;
    }

    // ...[생략]...

    /* Map wrc string to wide-character wdst string in alternate case */
    if (__acrt_LCMapStringW(
                plocinfo->locinfo->locale_name[LC_CTYPE],
                LCMAP_LOWERCASE,
                wsrc,
                -1,
                wdst.get(),
                dstsize
                ) != 0)
    {
        /* Copy wdst string to user string */
        return wcscpy_s(wsrc, sizeInWords, wdst.get());
    }
    // ...[생략]...
}

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\internal\winapi_thunks.cpp
extern "C" int WINAPI __acrt_LCMapStringEx(
    LPCWSTR          const locale_name,
    DWORD            const flags,
    LPCWSTR          const source,
    int              const source_count,
    LPWSTR           const destination,
    int              const destination_count,
    LPNLSVERSIONINFO const version,
    LPVOID           const reserved,
    LPARAM           const sort_handle
    )
{
    if (auto const lc_map_string_ex = try_get_LCMapStringEx()) // lc_map_string_ex == {KernelBase.dll!LCMapStringEx(void)}
    {
        return lc_map_string_ex(locale_name, flags, source, source_count, destination, destination_count, version, reserved, sort_handle);
    }
    // ...[생략]...
}

마지막으로, 'ß' 문자(U+00DF: Latin Small Letter Sharp S)의 대문자가 2017년부터는 ('SS'가 아닌) 'ẞ' 문자(U+1E9E: Latin Capital Letter Sharp S)로 바뀌었다고 하는데요, 하지만 현재의 ICU 라이브러리는 그전의 규칙으로 변환하고 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/11/2025]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  [23]  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13363정성태6/7/202312018스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/202311292.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/202311883오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/202310853오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/202311387오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/202311778.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/202311229.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/202312429DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/202311603.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/202312769.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/202312039.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/202312562VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/202311651오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/202312076.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제 [1]파일 다운로드1
13348정성태5/10/202312754.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/202313174.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/202312539오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/202314743.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/202315446.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/202313152디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/202311909.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/202311737닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/202312051오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/202313245닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/202311818닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/202312839Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
... 16  17  18  19  20  21  22  [23]  24  25  26  27  28  29  30  ...