Logo

Programming-Idioms

History of Idiom 63 > diff from v37 to v38

Edit summary for version 38 by tkoenig:
New Fortran implementation by user [tkoenig]

Version 37

2019-09-28, 16:15:52

Version 38

2019-09-29, 12:43:45

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Extra Keywords
substring substitute
Extra Keywords
substring substitute
Code
  character(len=:), allocatable :: x
  character(len=:), allocatable :: x2
  character(len=:), allocatable :: y,z
  integer :: j, k

  do
     j = index(x(k:),y)
     if (j==0) then
        x2 = x2 // x(k:)
        exit
     end if
     if (j>1) then
        x2 = x2 // x(k:j+k-2)
     end if
     x2 = x2 // z
     k = k + j + len(y) - 1
  end do
Comments bubble
This code uses reallocation on assignment for character variables. An alternative implementation might count bytes first, then allocate, then do this.