Replace all occurrences of s1
in str
with s2
.
A case-sensitive match is used.
Note
str
must be allocated.
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(kind=CK, len=:), | intent(inout), | allocatable | :: | str | ||
character(kind=CK, len=*), | intent(in) | :: | s1 | |||
character(kind=CK, len=*), | intent(in) | :: | s2 |
pure subroutine replace_string(str,s1,s2) implicit none character(kind=CK,len=:),allocatable,intent(inout) :: str character(kind=CK,len=*),intent(in) :: s1 character(kind=CK,len=*),intent(in) :: s2 character(kind=CK,len=:),allocatable :: tmp !! temporary string for accumulating result integer(IK) :: i !! counter integer(IK) :: n !! for accumulating the string integer(IK) :: ilen !! length of `str` string integer(IK) :: ilen1 !! length of `s1` string if (len(str)>0) then tmp = CK_'' ! initialize ilen1 = len(s1) ! . ! '123ab789' do ilen = len(str) i = index(str,s1) if (i>0) then if (i>1) tmp = tmp//str(1:i-1) tmp = tmp//s2 ! replace s1 with s2 in new string n = i+ilen1 ! start of remainder of str to keep if (n<=ilen) then str = str(n:ilen) else ! done exit end if else ! done: get remainder of string tmp = tmp//str exit end if end do str = tmp end if end subroutine replace_string