A method in C to find the position of a character in a string

  • 2020-04-02 03:17:49
  • OfStack

C STRCHR () function: looks for the first position of a character in a string

Header: #include < String. H >

STRCHR () is used to find the first position of a character in a string. The prototype is:


  char * strchr (const char *str, int c);

[parameter] STR is the string to be found, and c is the character to be found.

STRCHR () will find the address of the first occurrence of the character c in the STR string and return that address.

Note: the end flag NUL of the string STR is also retrieved, so the last character of the STR group can also be located.

Returns the address of the specified character if found, otherwise NULL.

The address returned is the random memory address of the string plus the character you are searching for in the string position. If the character first appears in the string at the position I, the returned address can be interpreted as STR + I.

Tip: if you want to find the last position of a character in a string, you can use the STRRCHR () function.

Example: find the location where character 5 first appears.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
  char *s = "0123456789012345678901234567890";
  char *p;
  p = strchr(s, '5');
  printf("%ldn", s);
  printf("%ldn", p);
  system("pause");
  return 0;
}

Output results:


12016464
12016469

 

C STRRCHR () function: finds the last position of a character in a string

Header: #include < String. H >

The STRRCHR () function is used to find the last position of a character in a string. The prototype is:


  char * strrchr(const char *str, int c);

[parameter] STR is the string to be found, and c is the character to be found.

STRRCHR () will find the address of the last occurrence of the character c in the STR string and return that address.

Note: the end flag NUL of the string STR is also retrieved, so the last character of the STR group can also be located.

Returns the last position of the character if found, otherwise NULL.

The address returned is the random memory address of the string plus the character you are searching for in the string position. If the character first appears in the string at the position I, the returned address can be interpreted as STR + I.

Tip: if you want to find the first place a character appears in a string, you can use the STRCHR () function.

Example: find the last location of character 5.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
  char *s = "0123456789012345678901234567890";
  char *p;
  p = strrchr(s, '5');
  printf("%ldn", s);
  printf("%ldn", p);
  system("pause");
  return 0;
}

Execution results:


12999504
12999529


Related articles: