首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言字串查找字元:手寫 strchr 邏輯與指針遍歷

     編輯:關於C

手寫 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; // 未找到
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved