Commit be1242be authored by Zolnierczuk, Piotr's avatar Zolnierczuk, Piotr
Browse files

added count_words subroutine

it's a brute force counting
parent e1e9c6ee
Loading
Loading
Loading
Loading
+30 −1
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ module strings_module

  private

  public :: split, tolower, toupper, simple_glob
  public :: split, tolower, toupper, simple_glob, count_words
  public :: replace_char, replace_str
  public :: string_replace ! function
  public :: is_number, is_integer
@@ -81,6 +81,35 @@ contains
  end subroutine split


  ! -------------------------------------------------------------------
  !> count words (brute force)
  function count_words(string, separator) result(nwords)
    integer :: nwords
    character(len=*), intent(in) :: string
    character(len=*), intent(in) :: separator
    !
    integer :: pos1, pos2, str_len
    nwords = 0
    pos1 = 1
    pos2 = 0
    str_len = len_trim(string)
    do
        pos2 = index(string(pos1:), separator)
        if ( pos2 <= 0 ) then
            if ( len_trim(string(pos1:)) >0 ) then
                nwords = nwords + 1
            end if
            return
        end if
        if ( len_trim(string(pos1:pos1+pos2-2))>0 ) then
          nwords = nwords + 1
       endif
       pos1 = pos2 + pos1
       if ( pos1 > str_len ) return
    end do
  end function count_words


  ! -------------------------------------------------------------------
  !> string replace function
  !! replace one of the characters from oldchars by a newchar character
+11 −1
Original line number Diff line number Diff line
@@ -33,6 +33,7 @@ program teststrings
     ' rampample                              ']

  call test_case_strings    ! tolower, toupper
  call test_count_words     ! count_words
  call test_split_strings   ! split
  call test_replace_strings ! replace_char, replace_str
  call test_simple_glob     ! match against a simple wildcard
@@ -67,6 +68,15 @@ contains
  end subroutine test_case_strings


  subroutine test_count_words
    integer :: nwords
    !
    write(*,*) '=========== count words ==============='
    write(*,'(1x,a)'   , advance='yes') ' original : '//trim(long_string)
    nwords = count_words(long_string, ' ')
    write(*,'(1x,a,i0)', advance='yes') ' nwords   : ', nwords
  end subroutine test_count_words


  subroutine test_split_strings
    character(len=MAX_TOKLEN), dimension(MAX_WORDS) :: word = "  "