join_string Function

private pure function join_string(strings, separator)

Joins a list of strings with a separator (default: space). Returns a new string

Arguments

Type IntentOptional Attributes Name
type(string_type), intent(in) :: strings(:)
character(len=*), intent(in), optional :: separator

Return Value type(string_type)


Called by

proc~~join_string~~CalledByGraph proc~join_string join_string interface~join join interface~join->proc~join_string

Variables

Type Visibility Attributes Name Initial
integer, private :: i
character(len=:), private, allocatable :: joined
integer, private :: lt
integer, private :: ltot
integer, private :: pos
character(len=:), private, allocatable :: sep

Source Code

   pure type(string_type) function join_string(strings, separator)
      type(string_type), intent(in) :: strings(:)
      character(len=*), intent(in), optional :: separator
      integer :: ltot, i, lt, pos
      character(len=:), allocatable :: sep, joined
      ! Determine separator: use user-provided separator or default space
      if (present(separator)) then
         sep = separator
      else
         sep = " "
      end if
      ! Calculate the total length required, including separators
      ltot = sum(len_trim(strings)) + (size(strings) - 1)*len(sep)
      allocate (character(len=ltot) :: joined)

      ! Concatenate strings with separator
      pos = 0
      do i = 1, size(strings)
         lt = len_trim(strings(i))
         joined(pos + 1:pos + lt) = char(strings(i), 1, lt)
         pos = pos + lt
         if (i < size(strings)) then
            joined(pos + 1:pos + len(sep)) = sep
            pos = pos + len(sep)
         end if
      end do

      ! Assign the result instead of moving into it. `move` passes this
      ! function's own result variable to an intent(out) dummy whose deferred
      ! length allocatable component is then filled by move_alloc, and both
      ! PGI-derived front ends (classic flang in AOCC 5.1.0, and nvfortran)
      ! leave the result unallocated, so join returned an empty string. This
      ! was the only `move` call in the library, so nothing else was exposed
      ! to it. Defined assignment of a character to a string_type is used
      ! everywhere and behaves on every target compiler; the extra copy of an
      ! already-built buffer is not measurable here.
      join_string = joined

   end function join_string