remove_characters_in_set Subroutine

public subroutine remove_characters_in_set(string, set, replace_with)


Type IntentOptional Attributes Name
character(len=:), intent(inout), allocatable :: string
character(len=*), intent(in) :: set
character(len=1), intent(in), optional :: replace_with


Source Code

subroutine remove_characters_in_set(string,set,replace_with)
    character(len=:), allocatable, intent(inout) :: string
    character(*), intent(in) :: set
    character, optional, intent(in) :: replace_with ! Replace with this character instead of removing

    integer :: feed,length

    if (.not.allocated(string)) return
    if (len(set)<=0) return

    length = len(string)
    feed   = scan(string,set)

    do while (length>0 .and. feed>0)

        ! Remove heading
        if (length==1) then
            string = ""

        elseif (feed==1) then
            string = string(2:length)

        ! Remove trailing
        elseif (feed==length) then
            string = string(1:length-1)

        ! In between: replace with given character
        elseif (present(replace_with)) then
            string(feed:feed) = replace_with
        ! Or just remove
            string = string(1:feed-1)//string(feed+1:length)
        end if

        length = len(string)
        feed   = scan(string,set)

    end do

end subroutine remove_characters_in_set