Search code examples
stringfortran

Fortran: remove characters from a string


How do I remove characters from a string?

For example, I have a string called 'year', which I want to change from 4 characters to 2 chracters. It is defined like so:

character(4) :: year = "2011"

How do I truncate the string to 2 characters, so that instead of year = "2011", it is year = "11"?


Solution

  • You can indeed use year(3:4); however, your string will still be four characters long, i.e. it will contain your two digits, and two blanks. To illustrate this, here's an example:

    program trunc
       character(len=4) :: year = "2011"
    
       write(*,'(A,A,A)') '..', year, '..'
       year = year(3:4)
       write(*,'(A,A,A)') '..', year, '..'
    end program trunc
    

    This prints

    ..2011..
    ..11  ..
    

    To really get "11" instead of "11 " you have to assign the value to a variable that can hold two characters only.