mknight
mknight

Reputation: 61

Fortran - Pulling Strings Containing Only Specified Characters

I have a Fortran project that I am working on that requires scanning through a database and storing strings that only contain characters specified by a reference string.

For example, supposed I have a reference string "A11." The database contains several pieces of data some of which contain all of the characters in the reference and some that do not, the following set is an example of this:

"A111,
"A211"
"B11"
"1AA1"

In this case, the program only pulls "A111," and "1AA1," because the other strings contain characters not in the reference string "A11."

I tried using a variant of this code, but it doesn't seem to work. Any help would be greatly appreciated.

 program main
 implicit none
 integer :: iostatus, i
 character*6, dimension(:), allocatable :: mystr_temp
 character*6 :: refstr
 open(unit=2,file='file.txt')
 iostatus = 1
 i = 1
 refstr = 'Ref'
 mystr(1) = ''
 do while (iostatus > 0)
      do while (any(mystr(i)) /= any(refstr))
           read(2,'(A6)', iostat = iostatus) mystr(i)
      end do
      i = i + 1
 end do
 end program main

Upvotes: 1

Views: 357

Answers (1)

roygvib
roygvib

Reputation: 7395

We can probably do this by using verify(str1,str2), which returns the location of the first character in str1 not present in str2. If all the characters in str1 are found in str2, the function returns 0. So I have modified the code such that

program main
    implicit none
    integer :: ios, i
    character(6) :: mystr(100), refstr, stmp
    open(unit=2,file='file.txt')

    i = 0
    refstr = 'A11'
    do
        read(2, '(a6)', iostat=ios) stmp
        if ( ios /= 0 ) exit
        if ( verify( stmp, refstr ) == 0 ) then
            i = i + 1
            mystr(i) = stmp
            print *, i, ":", mystr(i)
        endif
    enddo
end program

which gives for the sample data in the question

       1 :A111
       2 :1AA1

Upvotes: 1

Related Questions