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"
?
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.
I think it's year(3:4)
but don't quote me on it ;)
You can use year(3:4)
with year
declared as a deferred-length character to avoid trailing spaces. This is a Fortran 2003 feature so you need a compiler compatible with that, and you cannot initialize the variable in the declaration.
Example:
program deflen
implicit none
character(len=:), allocatable :: year
year = '2011'
write(*,'(A,A,I0)') year,'_LEN=', LEN(year)
year = year(3:4)
write(*,'(A,A,I0)') year,'_LEN=', LEN(year)
end program deflen
This prints:
2011_LEN=4
11_LEN=2
Use the following:
character(4) :: year = "2011"
character(2) :: yr2
yr2 = trim(year(3:4))
Here yr2
is the intended two character string.
精彩评论