In Fortran, how can I remove a specific string from another string? For example: string1='c/test/run1/runfile.dat', string2='runfile.dat'. I want to remove string2 ('runfile.dat') from string1('c/test/run1/runfile.dat') and get the result as 'c/test/run1/' How can I do that. I am using Fortran f90, with visual studio.
CodePudding user response:
May be this is too obvious, or I haven't understood your problem properly, but if you know that substring string2
has m
characters (len_trim()
) and really appears at the end of string1
that has n
characters, you can just use the first n-m
characters of string1
string1(1:n-m)
or in full
string1(1:len_trim(string1)-len_trim(string2))
You can verify that string2
really appears in string1
and find the position, using index()
as stated in the comments, but if you know it is there, just take the substring.
CodePudding user response:
If you want a library to do it then please have a look at the StringiFor.
In particular, see the following example.
Solution 2
You can use the following code which I have returned for you.
PROGRAM main
USE iso_fortran_env, ONLY: dfp => real64, i4b => int32, stdout => output_unit
IMPLICIT NONE
CHARACTER(len=:), ALLOCATABLE :: master
CHARACTER(len=:), ALLOCATABLE :: slave
CHARACTER(len=:), ALLOCATABLE :: ans
INTEGER(i4b) :: indx_start, slave_len, indx_end, master_len
!! main
master = 'c/test/run1/runfile.dat'
master_len = LEN_TRIM(master)
slave = 'runfile.dat'
slave_len = LEN_TRIM(slave)
indx_start = INDEX(master, slave)
IF (indx_start .EQ. 0) THEN
WRITE (stdout, "(a)") TRIM(slave)//" not found in "//TRIM(master)
ans = TRIM(master)
ELSE
WRITE (stdout, "(a)") TRIM(slave)//" found in "//TRIM(master)
ans = master//master(1:indx_start - 1)//master(indx_start slave_len:master_len)
END IF
WRITE(stdout, "(a)") "ans : " // TRIM(ans)
END PROGRAM main
Regards Vikas