Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

[Fortran] 文字列

Last updated at Posted at 2020-11-23

文字列の定義

character(len=)で指定した長さは代入する値に依らず一定

代入する値がlenよりも長い場合,末尾から切り捨てられる

character(len=3) :: text
text = 'a'
write(*, *) text, len(text) ! a 3
text = 'abc'
write(*, *) text, len(text) ! abc 3
text = 'abcde'
write(*, *) text, len(text) ! abc 3

割付可能な文字列

character(len=:), allocatable :: str(:)
allocate(character(10) :: arg)
deallocate(arg)

「割付可能な文字列」の配列

character(len=:), allocatable :: array(:)
integer :: clen, arrsize
allocate(character(clen) :: str(arrsize))

https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/287349
今のところは必要になっていないが,配列中の各要素の長さを変えるにはtypeを使うしかない?

処理

文字列の左/右寄せはadjustl/adjustr

https://jp.xlsoft.com/documents/intel/cvf/vf-html/az/az02_09.htm
https://jp.xlsoft.com/documents/intel/cvf/vf-html/az/az02_10.htm

writeの書式フォーマットとの関係 ('(a*)')

文字列の長さ (len=で指定する長さ) に対して

  • '(a*)'が短い: 左から出力,末尾は切り捨て
  • '(a*)'が長い: 右寄せで出力 (adjustlをつけても同じ)
    • 左寄せで出力するにはそれ以上の長さの文字列に一旦代入
      • 自分使い用ならlen=256などで決め打ち, より安全には上記の割付可能文字列
      • 更にtrimをすると右寄せに戻ってしまうので注意
character(len=3) :: text3
character(len=5) :: text5
character(len=7) :: text7
text3 = 'abc'
write(*, '(a1,a3,a1)') '(', text3, ')' ! (abc)
write(*, '(a1,a1,a1)') '(', text3, ')' ! (a)
write(*, '(a1,a5,a1)') '(', text3, ')' ! (  abc) 右寄せ
text5 = text3
write(*, '(a1,a5,a1)') '(', text5, ')' ! (abc  ) 左寄せ
text7 = text3
write(*, '(a1,a5,a1)') '(', text7, ')' ! (abc  ) 左寄せ
write(*, '(a1,a5,a1)') '(', trim(text5), ')' ! (  abc) 右寄せ
write(*, '(a1,a5,a1)') '(', trim(text7), ')' ! (  abc) 右寄せ
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?