1

I am trying to find the position of a character in a string using the following code.

implicit none
character string(10);
string="abcdefghik"
print *, index(string, "c")
end program test

But the output is 10 times 0 instead of 3. The same happens with the scan function.

What am I doing wrong?

francescalus
  • 30,576
  • 16
  • 61
  • 96
  • Although the linked question is about `character*10` this is the same as for `character(10)`. Both these declare a scalar of length 10 instead of an array of size 10. That you are mistakenly declaring as an error leads to the unexpected result. – francescalus Aug 20 '19 at 15:38
  • I must admit that this question actually introduces a lot of features: _Character arrays vs strings, elemental functions, assignment of a scalar value to an array_ and _assignement of unequal length character strings_ – kvantour Aug 21 '19 at 09:08
  • 2
    @kvantour, yes, but only because of a single (important and non-obvious) misunderstanding of the character declaration. – francescalus Aug 21 '19 at 09:44

1 Answers1

2

The bug:

You defined your string as an array of single characters of length 10:

character :: string(10)

A character string of length 10 is defined as

character(len=10) :: string

These two are two different concepts. See:

Why do I get 10 zeros?

The reason you obtained 10 times the value zero is because both INDEX and SCAN are elemental functions. This means that they execute for every element of the array. But this is not all, you would imagine that it would at least return ones the number 1 for the third array ellement. Unfortuntately, the assignment

character array(10)
array = "abcdefghik"
print *, array

will assign 10 times the letter a. You notice that this will return aaaaaaaaaa. This is due to array assignments.

Working code:

program test
  implicit none
  character(len=10) :: string;
  string="abcdefghik"
  print *, index(string, "c")
end program test
kvantour
  • 25,269
  • 4
  • 47
  • 72