티스토리 뷰

개발/C++

[ C++] StringUtil Class

-=HaeJuK=- 2024. 4. 22. 13:16
반응형
#pragma once

#include <format>

class cStringUtil
{

public:
    static std::wstring MBSToWCS( const std::string& _ssMbsStr, UINT _nCodePage = CP_UTF8 );
        // 유니코드 문자열을 멀티바이트 문자열로 변환
    static std::string WCSToMBS( const std::wstring& _ssWcs, UINT _nCodePage = CP_UTF8 );

    // Format 함수는 가변 인수를 받아 들여 std::wstring을 포맷합니다.
    template<typename... Args>
    static std::wstring Format( const std::wstring& format, Args&&... args ) {
        return std::vformat( format, std::make_wformat_args( std::forward<Args>( args )... ) );
    }

    // Format 함수는 가변 인수를 받아 들여 std::string을 포맷합니다.
    template<typename... Args>
    static std::string Format( const std::string& format, Args&&... args ) {
        return std::vformat( format, std::make_format_args( std::forward<Args>( args )... ) );
    }

};

#include "pch.h"
#include "cStringUtil.h"
#include <string>
#include <format>
#include <stdexcept>

// 멀티바이트 문자열을 유니코드 문자열로 변환
std::wstring cStringUtil::MBSToWCS( const std::string& _ssMbsStr, UINT _nCodePage )
{
    if( _ssMbsStr.empty() )
        return std::wstring();

    int len = MultiByteToWideChar( _nCodePage, 0, _ssMbsStr.c_str(), -1, NULL, 0 );
    if( len == 0 )
    {
        throw std::runtime_error( "Failed to convert MBS to WCS. Error: " + std::to_string( GetLastError() ) );
    }

    std::wstring ssWcs( len - 1, L'\0' );
    if( MultiByteToWideChar( _nCodePage, 0, _ssMbsStr.c_str(), -1, ssWcs.data(), len ) == 0 )
    {
        throw std::runtime_error( "Failed to convert MBS to WCS. Error: " + std::to_string( GetLastError() ) );
    }

    return ssWcs;
}

// 유니코드 문자열을 멀티바이트 문자열로 변환
std::string cStringUtil::WCSToMBS( const std::wstring& _ssWcs, UINT _nCodePage )
{
    if( _ssWcs.empty() )
        return std::string();

    int len = WideCharToMultiByte( _nCodePage, 0, _ssWcs.c_str(), -1, NULL, 0, NULL, NULL );
    if( len == 0 )
    {
        throw std::runtime_error( "Failed to convert WCS to MBS. Error: " + std::to_string( GetLastError() ) );
    }

    std::string ssMbs( len - 1, '\0' );
    if( WideCharToMultiByte( _nCodePage, 0, _ssWcs.c_str(), -1, ssMbs.data(), len, NULL, NULL ) == 0 )
    {
        throw std::runtime_error( "Failed to convert WCS to MBS. Error: " + std::to_string( GetLastError() ) );
    }

    return ssMbs;
}
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함