溫馨提示×

C語言strstr函數的用法是什么

小億
157
2023-11-14 16:12:45
欄目: 編程語言

C語言中的strstr函數用于在一個字符串中查找子串的位置。

函數原型如下:

char *strstr(const char *haystack, const char *needle);

參數:

  • haystack:要在其中查找子串的字符串。
  • needle:要查找的子串。

返回值:

  • 如果找到了子串,返回指向子串在原字符串中第一次出現的位置的指針。
  • 如果沒找到子串,返回NULL。

示例:

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

int main() {
    char str[] = "Hello, World!";
    char sub[] = "World";
    char *result;

    result = strstr(str, sub);
    if(result == NULL) {
        printf("Subtring not found!\n");
    } else {
        printf("Substring found at index: %ld\n", result - str);
    }

    return 0;
}

輸出:

Substring found at index: 7

在上述示例中,我們在字符串"Hello, World!“中查找子串"World”,并找到了它在位置7處。注意,返回的指針是相對于原字符串的偏移量,可以通過減去原字符串的指針來得到子串在原字符串中的索引。如果沒找到子串,返回NULL。

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