手寫 is_in 函式 (類 strchr)
#include
// 回傳 1 找到, 0 未找到
int is_in(const char *str, char target) {
while (*str) { // *str != '\0'
if (*str == target) return 1;
str++; // 移至下一字元
}
return 0;
}
int main() {
const char *s = "abcdefgh";
char c = 'd';
printf("%s\n", is_in(s, c) ? "存在" : "不存在"); // 存在
return 0;
}
標準庫替代
#include
if (strchr(s, c)) puts("存在"); // 找字元
if (strstr(s, "cd")) puts("存在"); // 找子字串
指針遍歷核心模式
while (*p) { /* 處理 *p */ p++; } // 遍歷字串直到 \0
for (; *p; p++) { /* ... */ } // 等價 for 寫法
進階:找到位置索引
int find_index(const char *s, char c) {
for (int i = 0; s[i]; i++)
if (s[i] == c) return i;
return -1; // 未找到
}