strchr()函数 和 strrchr() 函数

strchr

定义于头文件 <string.h>
char *strchr( const char *str, int ch );
寻找ch(按照如同(char)ch的方式转换成char后)在str所指向的空终止字节字符串(每个字符都被看做unsigned char)中的首次出现位置。终止的空字符被认为是字符串的一部分,并且能在寻找''时被找到。
若str不是指向空终止字节字符串的指针,则行为未定义。
参数
str - 指向待分析的空终止字节字符串的指针
ch - 要查找的字符
返回值
指向str找到的字符的指针,在未找到该字符时返回空指针。
示例

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in "%s"...
",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d
",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}
/*Looking for the 's' character in "This is a sample string"... 
found at 4 
found at 7 
found at 11 
found at 18*/

strrchr 

定义于头文件 <string.h>
const char *strrchr( const char *str, int ch );
char *strrchr( char *str, int ch );
找到最后一次出现的字符ch中的字节串所指向的str.

参数
str - NULL结尾的字节串的指针来进行分析

ch - 搜索字符

返回值
str,或NULL找到的字符的指针,如果没有这样的字符被找到

示例

/* strrchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  pch=strrchr(str,'s');
  printf ("Last occurence of 's' found at %d 
",pch-str+1);
  return 0;
}
/*Last occurence of 's' found at 18 */

  

原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/6203511.html