2022年6月28日星期二

C strchr

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

函式功能:在字串裡面搜尋指定字元,並回傳該字元所在字串中的位址

範例程式碼

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main(void)
  5. {
  6. char String1[12] = "hello world";
  7. char *ptr;
  8. int find_ch = 'o';
  9.  
  10. ptr = strchr( String1, find_ch );
  11. printf( "'%c' first show at '%s'\n",find_ch, ptr );
  12.  
  13. }


延伸

我們已經知道了strchr 會回傳搜尋字元第一次出現在字串中的位址,那可不可以知道是在陣列中的第幾個呢? 這其實是沒有問題的,程式碼如下
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main(void)
  5. {
  6. char String1[12] = "hello world";
  7. char *ptr;
  8. int find_ch = 'o';
  9. int Location = 0;
  10. ptr = strchr( String1, find_ch );
  11. printf( "'%c' first show at '%s'\n",find_ch, ptr );
  12. Location = ptr - (int)(&String1);//透過兩個位址相減得到字元所在位置
  13. printf("%c is at String1[%d]\n",find_ch,Location);
  14.  
  15. }

參考資料

https://www.tutorialspoint.com/c_standard_library/c_function_strchr.htm

https://zh.m.wikipedia.org/zh-tw/String.h#%E5%87%BD%E6%95%B0

https://www.ibm.com/docs/en/i/7.1?topic=functions-strchr-search-character


沒有留言:

發佈留言

打賞按讚