Fortran code snippets

Thanks. I should have compiled with gfortran -fbounds-check. A module that fixes the errors, incorporating the suggestions, is

module mystrings
  implicit none
  private
  public :: words
contains
  pure function words(string) result(word_arr)
    ! Returns an allocatable array of character strings.
    ! Each element’s length equals the length of the longest word.
    character(len=*), intent(in)  :: string
    character(len=:), allocatable :: word_arr(:)
    integer :: lenStr, i, start, endPos, numWords, maxLen
    character (len=1), parameter :: sep = " "
    ! Determine effective length of the input string (ignoring trailing spaces)
    lenStr = len_trim(string)
    numWords = 0
    maxLen   = 0
    i = 1

    ! First pass: count words and determine maximum word length.
    do while (i <= lenStr)
      if (string(i:i) /= sep) then
        start = i
        do
           if (i > lenStr) exit
           if (string(i:i) == sep) exit
           i = i + 1
        end do
        endPos = i - 1
        numWords = numWords + 1
        if (endPos - start + 1 > maxLen) maxLen = endPos - start + 1
      else
        i = i + 1
      end if
    end do

    ! Allocate the output array with each element having length maxLen.
    allocate(character(len=maxLen) :: word_arr(numWords))

    ! Second pass: extract each word into the allocated array.
    i = 1
    numWords = 0
    do while (i <= lenStr)
      if (string(i:i) /= sep) then
        start = i
        do
           if (i > lenStr) exit
           if (string(i:i) == sep) exit
           i = i + 1
        end do
        endPos = i - 1
        numWords = numWords + 1
        word_arr(numWords) = string(start:endPos)
      else
        i = i + 1
      end if
    end do
  end function words
end module mystrings
1 Like