strchr()函數 和 strrchr() 函數


strchr

定義於頭文件 <string.h>
char *strchr( const char *str, int ch );
尋找ch(按照如同(char)ch的方式轉換成char后)在str所指向的空終止字節字符串(每個字符都被看做unsigned char)中的首次出現位置。終止的空字符被認為是字符串的一部分,並且能在尋找'\0'時被找到。
若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\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",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 \n",pch-str+1);
  return 0;
}
/*Last occurence of 's' found at 18 */

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM