# Fortran code snippets

**URL:** <https://fortran-lang.discourse.group/t/fortran-code-snippets/2150>\
**Category:** Uncategorized\
**Created:** [October 24, 2021, 1:39pm UTC](https://fortran-lang.discourse.group/t/fortran-code-snippets/2150 "2021-10-24T13:39:39Z")\
**Posts on this page:** 1\
**Showing post:** 94

<div class="post-metadata">

**Author:** ![Beliavsky](https://avatars.discourse-cdn.com/v4/letter/b/ba8739/32.png) [@Beliavsky](https://fortran-lang.discourse.group/u/Beliavsky)\
**Post date:** [April 3, 2025, 9:50pm UTC](https://fortran-lang.discourse.group/t/fortran-code-snippets/2150/94 "2025-04-03T21:50:01Z")

</div>

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

```fortran
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

```

---

_[View the full topic](https://fortran-lang.discourse.group/t/fortran-code-snippets/2150)._
