You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fortran中按位置索引提取字符串子串并按指定格式输出?

Fortran按索引截取字符串拼接输出解决方案

问题原因

你当前输出异常的核心原因有两个:

  1. 你将原字符串拆分为了单个数字的整数数组,使用默认列表导向输出(write(*,*))时,每个整数会自动补前导空格、占用固定宽度,导致输出多了大量冗余空格
  2. 没有控制输出格式,所以整数字段宽度不统一,也没有按两列输出的规则控制

优化后完整代码

program subsetfile
  implicit none
  integer :: io,tmp,n,m,i,ind,s
  integer, dimension (:), allocatable :: idx
  character(len=1000) :: arr
  character(len=1000) :: fn, fnpos
  character(len=:), allocatable :: out_str

  print*, "File name:"
  read*, fn
  print*, "Position file name:"
  read*, fnpos

  ! 读取索引文件
  open(unit=100, file=fnpos, status='old', action='read')
  n = 0
  do
    read(100,*,iostat=io)
    if (io/=0) exit
    n = n + 1
  end do
  close(unit=100)
  allocate (idx(n))
  open(unit=101, file=fnpos, status='old', action='read')
  do i=1,n
    read(101,*) idx(i)
  end do
  close(unit=101)

  ! 统计输入文件行数
  open(unit=102, file=fn, status='old', action='read')
  n = 0
  do
    read(102,*,iostat=io)
    if (io/=0) exit
    n = n + 1
  end do
  close(unit=102)

  ! 处理并输出结果
  open(unit=104, file = fn, status = 'old', action = 'read')
  open(unit=105, file = 'output.txt', status = 'replace')  
  do i=1,n
    read(104,*) ind, arr
    ! 直接按索引拼接字符,无需转整数数组
    out_str = ''
    do s = 1, size(idx)
        out_str = out_str // arr(idx(s):idx(s))
    end do
    ! 控制输出格式:I2对应行号占2位,1X是一个分隔空格,A输出拼接后的字符串
    write(105, '(I2,1X,A)') ind, trim(out_str)
  end do
  close(unit=104)
  close(unit=105)

  deallocate (idx)
  if(allocated(out_str)) deallocate(out_str)
end program subsetfile

修改点说明

  • 删掉了不必要的整数数组vec相关逻辑,直接对原字符串按索引取单个字符拼接,减少了不必要的类型转换步骤
  • 新增动态长度字符串out_str存储拼接后的结果,字符之间没有任何空格
  • 输出时使用显式格式控制符(I2,1X,A),严格控制为两列输出,第一列行号占2位,中间一个空格分隔,第二列直接输出拼接好的字符串,没有多余空格
  • 如果你的行号长度超过2位(比如超过99行),可以把I2改成I0,会自动适配整数的实际长度,不会出现截断问题,格式符改成(I0,1X,A)即可。

内容的提问来源于stack exchange,提问作者Fernando Brito Lopes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:09:04