1
char a[20]="this is";
cout<<strchr (a,'t')-a;

How can this (a,'t')-a" can show the index of the first appearance of the letter t?How does it work? Someone said that the compiler makes the sum of ASCII characters,then subtracts the determined character.

  • You can assure that someone that that was utter nonsense, for several reasons. – Jongware May 27 '15 at 14:58
  • ... By the way, as an experiment this is not really a good one. For instance, `cout << 't' - 't';` would also "show the index of the first appearance of 't'." So repeat your line and replace the `'t'` with all of the letters (and non-letters) that occur in the sample string. For fun, include one that does *not* appear in the sample string. – Jongware May 27 '15 at 15:01

3 Answers3

0

It is purely pointer arithmetic.

strchr (a,'t') returns the pointer to the character 't' in string a. a hold the address of the string.

strchr (a,'t')- a returns you the index of t within string a

Example: a has addrress 100 Address of h within a will be 101 ,

so you will get index 1 for character h

Steephen
  • 14,645
  • 7
  • 40
  • 47
0

x = strchr (a, 't') returns a pointer to the first occurrence of character t in the C string a. In your case this happens to be the same as address of the first character in a. This is also what the variable a points to.

By subtracting x - a your subtracting two addresses, which (thanks to pointer arithmetic magic) will give the index of 't' in a. It's zero, because x and a are equal. Nothing to do with ASCII really.

banach-space
  • 1,781
  • 1
  • 12
  • 27
0

strchr returns a pointer to the first found character in your string.

char str[] = "Some string with spaces";
char* ptr;
ptr = strchr(str, ' ');
while(ptr != 0)
{
    printf("Space on %d. place\n", ptr - str);
    ptr = strchr(ptr + 1, ' ');
}
ProXicT
  • 1,903
  • 3
  • 22
  • 46