replace_one_occurrence Function

private elemental function replace_one_occurrence(self, old, new) result(replaced)

Arguments

Type IntentOptional AttributesName
class(string), intent(in) :: self

The string.

character(kind=CK,len=*), intent(in) :: old

Old substring.

character(kind=CK,len=*), intent(in) :: new

New substring.

Return Value type(string)

The string with old replaced by new.

Description

Return a string with the first occurrence of substring old replaced by new.


Variables

TypeVisibility AttributesNameInitial
integer, public :: pos

Position from which replace old.

character(kind=CK,len=:), public, allocatable:: temporary

Temporary storage, workaround for GNU bug.


Source Code

  elemental function replace_one_occurrence(self, old, new) result(replaced)
  !---------------------------------------------------------------------------------------------------------------------------------
  !< Return a string with the first occurrence of substring old replaced by new.
  !---------------------------------------------------------------------------------------------------------------------------------
  class(string),             intent(in)  :: self      !< The string.
  character(kind=CK, len=*), intent(in)  :: old       !< Old substring.
  character(kind=CK, len=*), intent(in)  :: new       !< New substring.
  type(string)                           :: replaced  !< The string with old replaced by new.
  integer                                :: pos       !< Position from which replace old.
#ifdef __GFORTRAN__
  character(kind=CK, len=:), allocatable :: temporary !< Temporary storage, workaround for GNU bug.
#endif
  !---------------------------------------------------------------------------------------------------------------------------------

  !---------------------------------------------------------------------------------------------------------------------------------
  if (allocated(self%raw)) then
    replaced = self
    pos = index(string=self%raw, substring=old)
    if (pos>0) then
#ifdef __GFORTRAN__
      temporary = self%raw
      if (pos==1) then
        replaced%raw = new//temporary(len(old)+1:)
      else
        replaced%raw = temporary(1:pos-1)//new//temporary(pos+len(old):)
      endif
#else
      if (pos==1) then
        replaced%raw = new//self%raw(len(old)+1:)
      else
        replaced%raw = self%raw(1:pos-1)//new//self%raw(pos+len(old):)
      endif
#endif
    endif
  endif
  return
  !---------------------------------------------------------------------------------------------------------------------------------
  endfunction replace_one_occurrence