Removing whitespace in string

I have the following code:

  program main
     character (len=15) :: abc = "te st tex  t"
     print *, trim(abc)      
  end program main

Which outputs:

 te st tex  t

I excepted all the whitespace to be removed but it wasn't. How can I remove all the whitespace from the string?


  • Trim will remove spaces only at the edges, not in the middle (this is common behaviour on almost all languages/libraries). If you want to remove all spaces in the string, you will have to create your own function to do this, iterating through the string.


    program Test
    implicit none
        ! Variables
        character(len=200) :: string
        ! Body of Test
        string = 'Hello World              7    9'
        print *, string
        call StripSpaces (string)
        print *, string
        subroutine StripSpaces(string)
        character(len=*) :: string
        integer :: stringLen 
        integer :: last, actual
        stringLen = len (string)
        last = 1
        actual = 1
        do while (actual < stringLen)
            if (string(last:last) == ' ') then
                actual = actual + 1
                string(last:last) = string(actual:actual)
                string(actual:actual) = ' '
                last = last + 1
                if (actual < last) &
                    actual = last
        end do
        end subroutine
    end program Test

    This was tested on intel compiler, not on gfortran, but I think it will work.