如何在Fortran中向现有字符变量追加字符?为何连接操作未生效?
Fortran中字符串追加的正确方法
你遇到的问题根源在于Fortran的固定长度字符串特性:
你的old_str和new_str都被声明为长度8的固定字符串,初始赋值old_str="foo"后,old_str实际存储的是"foo "(后面补5个空格),new_str="bar"则是"bar "(后面补5个空格)。
当执行old_str = old_str//new_str时,字符串连接操作//会生成一个长度为8+8=16的新字符串:"foo bar "。但把这个16长度的字符串赋值回长度8的old_str时,Fortran会自动截断前8个字符,也就是"foo ",所以最终输出看起来和初始值一样。
方法1:用trim()获取有效字符串后连接
先通过trim()去掉原字符串末尾的空格,再和新字符串连接,最后赋值回原字符串(注意不要超过原字符串的总长度):
program teststr character(len=8) :: old_str, new_str old_str="foo" new_str="bar" old_str = trim(old_str)//new_str ! 先去掉old_str末尾空格再连接 print *, old_str end program
这段代码执行后,trim(old_str)是"foo",和new_str("bar ")连接得到"foobar ",赋值给长度8的old_str会截断为前8个字符"foobar ",打印出来就是foobar(末尾的空格在输出中可能不显眼,但确实完成了追加)。
方法2:精准定位字符串位置追加(推荐)
如果想更精确地控制追加,避免不必要的空格,可以先获取原字符串的有效长度,然后把新字符串的有效部分直接写入原字符串的对应位置:
program teststr character(len=8) :: old_str, new_str integer :: len_old, len_new old_str="foo" new_str="bar" len_old = len_trim(old_str) ! 获取old_str的有效字符长度(3) len_new = len_trim(new_str) ! 获取new_str的有效字符长度(3) ! 检查是否有足够空间追加 if (len_old + len_new <= len(old_str)) then old_str(len_old+1 : len_old+len_new) = trim(new_str) end if print *, old_str end program
这段代码会把new_str的有效部分"bar"直接写入old_str的第4到第6位,最终old_str变成"foobar ",输出结果符合预期。
内容的提问来源于stack exchange,提问作者bob.sacamento
相关产品推荐
相关产品推荐

