Logo

Programming-Idioms

History of Idiom 63 > diff from v39 to v40

Edit summary for version 40 by tkoenig:
[Fortran] Added remark about //

Version 39

2019-09-29, 13:52:22

Version 40

2019-09-29, 15:06:15

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
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.
Comments bubble
This code uses reallocation on assignment for character variables. An alternative implementation might count bytes first, then allocate, then do this.

Note that _// is string concatenation in Fortran.