insert_character Function

private elemental function insert_character(self, substring, pos) result(inserted)

Arguments

TypeIntentOptionalAttributesName
class(string), intent(in) :: self
character(len=*), intent(in) :: substring
integer, intent(in) :: pos

Return Value type(string)


Contents

Source Code


Source Code

   elemental function insert_character(self, substring, pos) result(inserted)
   !< Insert substring into string at a specified position.
   !<
   !<```fortran
   !< type(string)                  :: astring
   !< character(len=:), allocatable :: acharacter
   !< logical                       :: test_passed(5)
   !< astring = 'this is string example wow!!!'
   !< acharacter = '... '
   !< test_passed(1) = astring%insert(substring=acharacter, pos=1)//''=='... this is string example wow!!!'
   !< test_passed(2) = astring%insert(substring=acharacter, pos=23)//''=='this is string example...  wow!!!'
   !< test_passed(3) = astring%insert(substring=acharacter, pos=29)//''=='this is string example wow!!!... '
   !< test_passed(4) = astring%insert(substring=acharacter, pos=-1)//''=='... this is string example wow!!!'
   !< test_passed(5) = astring%insert(substring=acharacter, pos=100)//''=='this is string example wow!!!... '
   !< print '(L1)', all(test_passed)
   !<```
   !=> T <<<
   class(string),    intent(in) :: self      !< The string.
   character(len=*), intent(in) :: substring !< Substring.
   integer,          intent(in) :: pos       !< Position from which insert substring.
   type(string)                 :: inserted  !< Inserted string.
   integer                      :: safepos   !< Safe position from which insert substring.

   if (allocated(self%raw)) then
      inserted = self
      safepos = min(max(1, pos), len(self%raw))
      if (safepos==1) then
         inserted%raw = substring//self%raw
      elseif (safepos==len(self%raw)) then
         inserted%raw = self%raw//substring
      else
         inserted%raw = self%raw(1:safepos-1)//substring//self%raw(safepos:)
      endif
   else
      inserted%raw = substring
   endif
   endfunction insert_character