Last active
July 15, 2022 05:20
-
-
Save noqisofon/dd4d339426c60c84902bcc5dd92c6789 to your computer and use it in GitHub Desktop.
( ノ╹◡◡╹)ノ utf-8 な文字列を icu を使ってうまく処理したさを感じた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// via: http://yasuda.homeip.net/insomnia/2013/10/icu-cc-unicode-library.html | |
#include <unicode/schriter.h> | |
#include <unicode/ustream.h> | |
using UnicodeStringIterator = icu::StringCharacterIterator; | |
int main() { | |
/** msys2 の gcc だと(msys2 の gcc でしか試してないのでこう書いているが、gcc なら多分そうなる)ソースコードのエンコーディングが UTF-8 だと | |
以下の文字列は raw UTF-8 になる。 | |
raw utf-8 というのは、1 文字が 1 バイトずつ char 配列に入っているということ。 | |
icu::UnicodeString::fromUTF8() を使って icu::UnicodeString に変換する。 */ | |
auto u8_text = icu::UnicodeString::fromUTF8( "あいうえおかきくけこさしすせそ" ); | |
std::cout << "u8 text length: " << u8_text.length() << std::endl; // => u8 text length: 15 | |
std::cout << std::endl; | |
UnicodeStringIterator it( u8_text ); | |
for ( UChar ch = it.first(); ch != UnicodeStringIterator::DONE; ch = it.next() ) { | |
std::cout << "U+" << std::hex << ch << std::endl; | |
} | |
std::string raw_text; | |
/** ここで、0 番目から 5 文字を切り出す。 | |
こうすると、substringed_text には ”あいうえお”が入っていることになる。 */ | |
icu::UnicodeString substringed_text = u8_text.tempSubString( 0, 5 ); | |
/** それを表示したいが、utf-8 な icu::UnicodeString をそのまま表示しようとすると msys2 では矢印が表示される。 | |
これを回避するため、raw utf-8 な文字列(ここでは std::string)に変換する必要がある。 | |
これを行ってくれるのが、toUTF8String() である。 */ | |
//via: https://stackoverflow.com/questions/4386802/convert-icu-unicodestring-to-platform-dependent-char-or-stdstring | |
substringed_text.toUTF8String( raw_text ); | |
std::cout << std::endl; | |
std::cout << "raw text length: " << std::dec << raw_text.length() << std::endl; // => raw text length: 15 | |
std::cout << raw_text << std::endl; // => あいうえお | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
src0 = example_icu.cpp | |
obj0 = example_icu.o | |
objs = $(obj0) | |
target = example_icu | |
# icu_data_libs = -licudata | |
# icu_i18n_libs = -licui18n | |
icu_uc_libs = -licuuc | |
icu_io_libs = -licuio | |
icu_libs = $(icu_uc_libs) $(icu_io_libs) | |
pthread_libs = -lpthread | |
math_libs = -lm | |
libs = $(math_libs) $(pthread_libs) $(icu_libs) | |
all: $(target) | |
$(target): $(objs) | |
g++ $^ $(libs) -o $@ | |
$(obj0): $(src0) | |
g++ --std=c++17 -W -Wall -Wextra -O2 -c $^ -o $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment