merge_str(3f) - [M_strings:LENGTH] pads strings to same length and
then calls MERGE(3f)
(LICENSE:PD)
function merge_str(str1,str2,expr) result(strout)
character(len=*),intent(in),optional :: str1
character(len=*),intent(in),optional :: str2
logical,intent(in) :: expr
character(len=:),allocatable :: strout
merge_str(3f) pads the shorter of str1 and str2 to the longest length
of str1 and str2 and then calls MERGE(padded_str1,padded_str2,expr).
It trims trailing spaces off the result and returns the trimmed
string. This makes it easier to call MERGE(3f) with strings, as
MERGE(3f) requires the strings to be the same length.
NOTE: STR1 and STR2 are always required even though declared optional.
this is so the call "STR_MERGE(A,B,present(A))" is a valid call.
The parameters STR1 and STR2 when they are optional parameters
can be passed to a procedure if the options are optional on the
called procedure.
STR1 string to return if the logical expression EXPR is true
STR2 string to return if the logical expression EXPR is false
EXPR logical expression to evaluate to determine whether to return
STR1 when true, and STR2 when false.
MERGE_STR a trimmed string is returned that is otherwise the value
of STR1 or STR2, depending on the logical expression EXPR.
Sample Program:
program demo_merge_str
use M_strings, only : merge_str
implicit none
character(len=:), allocatable :: answer
answer=merge_str('first string', &
& 'second string is longer',10 == 10)
write(*,'("[",a,"]")') answer
answer=merge_str('first string', &
& 'second string is longer',10 /= 10)
write(*,'("[",a,"]")') answer
end program demo_merge_str
Expected output
[first string]
[second string is longer]
John S. Urban
Public Domain
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(len=*), | intent(in), | optional | :: | str1 | ||
character(len=*), | intent(in), | optional | :: | str2 | ||
logical, | intent(in) | :: | expr |
function merge_str(str1,str2,expr) result(strout)
! for some reason the MERGE(3f) intrinsic requires the strings it compares to be of equal length
! make an alias for MERGE(3f) that makes the lengths the same before doing the comparison by padding the shorter one with spaces
! ident_46="@(#) M_strings merge_str(3f) pads first and second arguments to MERGE(3f) to same length"
character(len=*),intent(in),optional :: str1
character(len=*),intent(in),optional :: str2
character(len=:),allocatable :: str1_local
character(len=:),allocatable :: str2_local
logical,intent(in) :: expr
character(len=:),allocatable :: strout
integer :: big
if(present(str2))then
str2_local=str2
else
str2_local=''
endif
if(present(str1))then
str1_local=str1
else
str1_local=''
endif
big=max(len(str1_local),len(str2_local))
! note: perhaps it would be better to warn or fail if an optional value that is not present is returned, instead of returning ''
strout=trim(merge(lenset(str1_local,big),lenset(str2_local,big),expr))
end function merge_str