여기에는 표준 C++을 사용하는 함수가 있습니다 (CharT
에 따라 일부 유효한 구현 정의 동작이 충족하지 못하는 요구 사항이있을 수 있음).
#include <codecvt>
#include <sstream>
#include <iomanip>
#include <iostream>
template<typename CharT,typename traits,typename allocator>
std::basic_string<CharT,traits,allocator>
to_uescapes(std::basic_string<CharT,traits,allocator> const &input)
{
// string converter from CharT to char. If CharT = char then no conversion is done.
// if CharT is char32_t or char16_t then the conversion is UTF-32/16 -> UTF-8. Not all implementations support this yet.
// if CharT is something else then this uses implementation defined encodings and will only work for us if the implementation uses UTF-8 as the narrow char encoding
std::wstring_convert<std::codecvt<CharT,char,std::mbstate_t>,CharT> convertA;
// string converter from UTF-8 -> UTF-32. Not all implementations support this yet
std::wstring_convert<std::codecvt<char32_t,char,std::mbstate_t>,char32_t> convertB;
// convert from input encoding to UTF-32 (Assuming convertA produces UTF-8 string)
std::u32string u32input = convertB.from_bytes(convertA.to_bytes(input));
std::basic_stringstream<CharT,traits,allocator> ss;
ss.fill('0');
ss << std::hex;
for(char32_t c : u32input) {
if(c < U'\U00010000')
ss << convertA.from_bytes("\\u") << std::setw(4) << (unsigned int)c;
else
ss << convertA.from_bytes("\\U") << std::setw(8) << (unsigned int)c;
}
return ss.str();
}
template<typename CharT>
std::basic_string<CharT>
to_uescapes(CharT const *input)
{
return to_uescapes(std::basic_string<CharT>(input));
}
int main() {
std::string s = to_uescapes(u8"Hello \U00010000");
std::cout << s << '\n';
}
이 인쇄해야합니다 :
\ u0048 \ u0065 \ u006c \ u006c \ u006f \ u0020 \ U00010000
당신이 그 일을하지 않았다 시도 했습니까? – geoffspear
프로그램 내부의 문자를 나타내는 데 사용하는 내부 형식은 무엇입니까? ASCII/UTF-8/UTF-16/UTF-32/CP1490/ISO8859-1? \ u 형식은 4 자리 16 진수 또는 6 자리 숫자 만 지원합니까? 4 만 지원하는 경우 4 자리 16 진수로 모든 코드 포인트를 나타낼 수 있으므로 UTF-16으로 인코딩하고 긴 문자에 대용 암호 쌍을 사용해야합니다. –