溫馨提示×

c語言的index函數怎么使用

小億
173
2023-12-15 00:02:28
欄目: 編程語言

C語言中沒有內置的index函數,但是可以使用strchr函數來實現類似功能。strchr函數用于在字符串中查找特定字符的第一次出現,并返回該字符的指針。

使用示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "hello world";
    char *ptr = strchr(str, 'o');  // 在str中查找字符'o'的第一次出現
    if (ptr != NULL) {
        printf("找到了字符'o',其在字符串中的位置為:%ld\n", ptr - str);
    } else {
        printf("未找到字符'o'\n");
    }
    return 0;
}

輸出結果:

找到了字符'o',其在字符串中的位置為:4

上述示例中,首先定義了一個字符串str,然后使用strchr(str, 'o')str中查找字符'o'的第一次出現。如果找到了字符'o',則返回該字符的指針,并通過指針相減得到字符在字符串中的位置。如果未找到字符'o',則返回NULL。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女