char *strchr(const char *string, int c);
函式功能:在字串裡面搜尋指定字元,並回傳該字元所在字串中的位址
範例程式碼
#include <stdio.h>
#include <string.h>
int main(void)
{
char String1[12] = "hello world";
char *ptr;
int find_ch = 'o';
ptr = strchr( String1, find_ch );
printf( "'%c' first show at '%s'\n",find_ch, ptr );
}
延伸
我們已經知道了strchr 會回傳搜尋字元第一次出現在字串中的位址,那可不可以知道是在陣列中的第幾個呢? 這其實是沒有問題的,程式碼如下#include <stdio.h>
#include <string.h>
int main(void)
{
char String1[12] = "hello world";
char *ptr;
int find_ch = 'o';
int Location = 0;
ptr = strchr( String1, find_ch );
printf( "'%c' first show at '%s'\n",find_ch, ptr );
Location = ptr - (int)(&String1);//透過兩個位址相減得到字元所在位置
printf("%c is at String1[%d]\n",find_ch,Location);
}
參考資料
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


沒有留言:
發佈留言