未知长度的字符返回函数 [英] Character-returning function of unknown length

查看:159
本文介绍了未知长度的字符返回函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



trim() 函数,我明白,表明可以不指定返回字符串的长度。



例如:

< pre $ write(*,*)trim(str)

将只返回字符串的一部分,不会有空格。



这个函数对调用之前返回字符串的长度没有任何意见。 b

trim()函数有局限性?

原始代码 trim()函数。



我发现(在fortran中返回长度不确定的字符串),但这不是我的问题的答案。 >

可以肯定,我想写一个函数,它返回整数nu的字符串



类似这样的:

  function strByInt(myInt) 
...
write(strByInt,fmt)myInt; ($,*)strByInt(50)!

$会写'50'


解决方案

它。它提到了可延迟长度的可分配字符。请参阅下面我经常使用的实现:

  function strByInt(i)result(res)
character(:), allocatable :: res
整数,意图(in):: i
字符(范围(i)+2):: tmp
write(tmp,'(i0)')i
res = trim(tmp)
结束函数

结果变量在赋值时分配在最后一行,以适应答案。


$ b $ < trim 函数是一个不同的野兽,作为一个内在的函数它不需要在Fortran中编程,并且可以遵守不同的规则。它只是返回它需要返回的内容。但它可以像上面那样很容易实现。


How to use character function of where the result is of unknown length initially?

The trim() function, I understand, shows that it is possible not to specify the length of returning string.

For example:

write (*,*) trim(str)

will return only part of the string without trailing spaces.

This function does not have any idea about the length of returning string before the call.

Or trim() function has limitations?

On more variant is to find original code of trim() function.

I have found (Returning character string of unknown length in fortran) but it is not the answer to my question.

To be sure, I want to write function, that returns string by integer number.

Something like this:

function strByInt(myInt)
...
write (strByInt,fmt) myInt; return
end function strByInt

somewhere else:

write (*,*) strByInt(50) ! will write '50'

解决方案

That question you referenced partially answers it. It mentions the allocatable characters with deferred length. See below my implementation I use regularly:

  function strByInt(i) result(res)
    character(:),allocatable :: res
    integer,intent(in) :: i
    character(range(i)+2) :: tmp
    write(tmp,'(i0)') i
    res = trim(tmp)
  end function

The result variable is allocated on assignment on the last line to fit the answer.

The trim function is a different beast, as an intrinsic function it doesn't have to be programmed in Fortran and can obey different rules. It just returns what it needs to return. But it could be as well implemented as above quite easily.

这篇关于未知长度的字符返回函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆