1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Fortran 文字列型にUFT-8の日本語を使用する際の考え方

Last updated at Posted at 2024-05-20

環境

OS: Ubuntu-22.04.04 LTS on WSL2
コンパイラ: gfortran version 11.4.0

結果

program char
    use, intrinsic :: iso_fortran_env
    implicit none
    character(len=10) :: string_list(5)

    ! 𢎭=UTF-8で4byte格納の難読漢字
    string_list = [character(len=10) :: "abc", "あいう", "あいうえお", "𢎭", "🍺"] 

    print *, string_list(2) ! あいう
    print *, string_list(2)(1:4) ! あ�
    print *, string_list(3) ! あいう�
    print *, string_list(4) ! 𢎭
    print *, string_list(4)(1:3) ! �
    print *, string_list(4)(1:4) ! 𢎭
    print *, string_list(5)(1:3) ! �
    print *, string_list(5)(1:4) ! 🍺

end program char

出力を見るとcharacter型はC言語と同様に8bitを1要素として機械的に取り入れて、機械的に出力しているようです。
UTF-8で、あるフォントに設定したコンソールに出力した際には、UTF-8に対応する文字フォントがあれば文字化けするこなく出力されるといった感じでしょうか。

あいうえおの場合はそれぞれ24bitなので、Fortranでは15文字としてカウントされcharacter(len=10)に明示的に変換される際にの途中まで格納された形になる。
𢎭という一部の難読漢字ではUTF-8で4byte格納になっているので4文字として格納される。
🍺という絵文字もUTF-8で4byte格納なので4文字分。

方針

実用的には、基本日本語は24bit(3文字)で決め打ち、32bitになるもの(一部の難読漢字や絵文字)は入らないものとしてあつかう(絵文字を入れるなと注意書きに書く)といった感じでしょうか。

終わりに

Fortranを使用する人は日本語を扱うことはあまりないと思われますが、一応書きました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?