partition Function

private pure function partition(self, sep) result(partitions)

Arguments

TypeIntentOptionalAttributesName
class(string), intent(in) :: self
character(kind=CK,len=*), intent(in), optional :: sep

Return Value type(string)(1:3)


Contents

Source Code


Source Code

   pure function partition(self, sep) result(partitions)
   !< Split string at separator and return the 3 parts (before, the separator and after).
   !<
   !<```fortran
   !< type(string) :: astring
   !< type(string) :: strings(3)
   !< logical      :: test_passed(3)
   !< astring = 'Hello WorLD!'
   !< strings = astring%partition(sep='lo Wo')
   !< test_passed(1) = (strings(1)//''=='Hel'.and.strings(2)//''=='lo Wo'.and.strings(3)//''=='rLD!')
   !< strings = astring%partition(sep='Hello')
   !< test_passed(2) = (strings(1)//''==''.and.strings(2)//''=='Hello'.and.strings(3)//''==' WorLD!')
   !< astring = 'Hello WorLD!'
   !< strings = astring%partition()
   !< test_passed(3) = (strings(1)//''=='Hello'.and.strings(2)//''==' '.and.strings(3)//''=='WorLD!')
   !< print '(L1)', all(test_passed)
   !<```
   !=> T <<<
   class(string),             intent(in)           :: self            !< The string.
   character(kind=CK, len=*), intent(in), optional :: sep             !< Separator.
   type(string)                                    :: partitions(1:3) !< Partions: before the separator, the separator itsels and
                                                                      !< after the separator.
   character(kind=CK, len=:), allocatable          :: sep_            !< Separator, default value.
   integer                                         :: c               !< Character counter.

   if (allocated(self%raw)) then
      sep_ = SPACE ; if (present(sep)) sep_ = sep

      partitions(1) = self
      partitions(2) = sep_
      partitions(3) = ''
      if (len(sep_)>=len(self%raw)) return
      c = index(self%raw, sep_)
      if (c>0) then
         partitions(1)%raw = self%raw(1:c-1)
         partitions(2)%raw = self%raw(c:c+len(sep_)-1)
         partitions(3)%raw = self%raw(c+len(sep_):)
      endif
   endif
   endfunction partition