fortran中提取字符串中可见字符的索引

fortran中常常需要提取字符串中可见字符的索引,下面是个小例子:

 

!=============================================================
subroutine TrimIndex(InStr,LeftIndex,RightIndex,status)
!------------------------------------------------------------
!---识别InStr中左右有效可见字符(33-126)的索引
!---如果status==0,则识别正确
!---吴徐平2013-07-20(wxp07@qq.com)
!------------------------------------------------------------
Implicit None
Character(Len =*),Intent( IN ) :: InStr
Integer,Intent( INOUT)::LeftIndex,RightIndex,status
!------------------------------------------------------------
Integer ::i
!------------------------------------------------------------
LeftIndex=0
do i=1,LEN(InStr),1
	if ((IACHAR(InStr(i:i)) >32 ).AND.(IACHAR(InStr(i:i)) <127) ) then
			LeftIndex=i !-左边有效可见字符(33-126)的索引
			EXIT
	end if
end do
!------------------------------------------------------------
RightIndex=LEN(InStr)+1
do i=LEN(InStr),1,-1
	if ((IACHAR(InStr(i:i)) >32 ).AND.(IACHAR(InStr(i:i)) <127 )) then
			RightIndex=i !-右边有效可见字符(33-126)的索引
			EXIT
	end if
end do
!--------------------------
if ((LeftIndex>0 ).AND. (LeftIndex<=RightIndex) .AND. (RightIndex<=LEN(InStr)))then
	status=0  !-操作正确
else
	status=-1 !-操作有误
end if
!--------------------------
end subroutine TrimIndex


 

下面是测试程序:

 

program TestTrimIndex
!-----------------------------------------
!测试TrimIndex的程序
!吴徐平 2013-07-20
!wxp07@qq.com
!编译:gfortran TestTrimIndex.f90
!-----------------------------------------
implicit none
integer :: count  !-命令行参数的个数
CHARACTER(len=24) :: InStr !命令行参数
Integer::LeftIndex,RightIndex,status,i
!-----------------------------------------
count = command_argument_count() !获取主程序命令行的输入参数的个数  
!------------------------------------  
if (count>0) then  
	do i=1,count
	    CALL get_command_argument(i, InStr)
	    call TrimIndex(InStr,LeftIndex,RightIndex,status)  
	    if (status==0)then
				write(*,*)'<'//InStr//'>'
				write(*,*)'<'//InStr(LeftIndex:RightIndex)//'>'
				write(*,*)LeftIndex
				write(*,*)RightIndex
			end if
	end do
else  
    write(*,*) 'You should input an argument!'
end if 
!------------------------------------  
end program

上面的子程序常用来查找字符串中第一个和最后一个不是空格字符的索引.

 

有图有真相,如下:



posted @ 2013-07-22 19:40  xinyuyuanm  阅读(883)  评论(0编辑  收藏  举报