Topic: String Index function

Was having difficulty with writting a program dealing with lots of character string manipulation.  After digging around I narrowed it down to the following behavior.  Perhaps I am missing something but the following seems to indicate a problem in the index function. Can someone please assist? running Build 3177

program testindex
implicit none

   character(len=30) :: myString
   character(len=20) :: testString
   myString = 'This is a test'
   testString = 'test'
   testString=adjustL(testString)
   if(index(myString, testString) == 0)then
      print *, 'test is not found'
   else
      print *, 'test is found at index: ', index(myString, testString)
   end if
end program testindex

output is:
test is found at index:           11

Result as expected however if you recompile but change len=20 to len =21 for teststring
i.e.
program testindex
implicit none

   character(len=30) :: myString
   character(len=21) :: testString
   myString = 'This is a test'
   testString = 'test'
   testString=adjustL(testString)
   if(index(myString, testString) == 0)then
      print *, 'test is not found'
   else
      print *, 'test is found at index: ', index(myString, testString)
   end if
end program testindex

output is:
test is not found

Re: String Index function

The issue is that the index function is not searching simply for "test."  It is actually searching for the following in quotes:

"test                 "

In the first case, the index function is looking for the word "test" followed by 16 spaces, which does occur in your string myString, but in the second case, looking for "test" followed by 17 spaces fails.

What you actually want to find is just the word "test."  You can use the trim() intrinsic in your call to the index() function to make sure it works properly:

index(myString, trim(test))

which will work as you'd expect.

Jeff Armstrong
Approximatrix, LLC

Re: String Index function

Thanks for the quick response to get me functional!!!! I had tried

  testString=TRIM(testString)
   if(index(myString, testString) == 0) then

but that did/does not work.
It appears that the trim must be inside the index call

Re: String Index function

The statement

testString=TRIM(testString)

essentially does nothing.  The RHS expression does produce a character string without the trailing blanks, but
then that string is assigned back to testString, which has a length greater than the trimmed string, so it gets blank filled on the right (i.e., back exactly like it was before this statement was executed).