strstr!!!

`strstr` 是 C 语言中的一个标准库函数,用于在一个字符串中查找子串。它的原型定义在 `string.h` 头文件中。`strstr` 函数

返回指向子串首次出现位置的指针,如果未找到子串,则返回 `NULL`。

函数原型

```c

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

```

**参数**:

  • `haystack`:要搜索的源字符串。

  • `needle`:要在 `haystack` 中搜索的子串。

**返回值**:

  • 返回一个指向 `haystack` 中 `needle` 第一次出现位置的指针。

  • 如果 `needle` 是空字符串,`strstr` 返回 `haystack` 的指针。

  • 如果 `needle` 未在 `haystack` 中找到,返回 `NULL`。

示例

下面是一个使用 `strstr` 的示例程序,演示了如何在一个字符串中查找子串:

复制代码
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World! This is a test string.";
    char substr1[] = "World";
    char substr2[] = "test";
    char substr3[] = "example";

    // 查找子串 "World"
    char *ptr1 = strstr(str, substr1);
    if (ptr1 != NULL) {
        printf("Found '%s' in string at position %ld\n", substr1, ptr1 - str);
    } else {
        printf("'%s' not found in string\n", substr1);
    }

    // 查找子串 "test"
    char *ptr2 = strstr(str, substr2);
    if (ptr2 != NULL) {
        printf("Found '%s' in string at position %ld\n", substr2, ptr2 - str);
    } else {
        printf("'%s' not found in string\n", substr2);
    }

    // 查找子串 "example"
    char *ptr3 = strstr(str, substr3);
    if (ptr3 != NULL) {
        printf("Found '%s' in string at position %ld\n", substr3, ptr3 - str);
    } else {
        printf("'%s' not found in string\n", substr3);
    }

    return 0;
}

输出

复制代码
Found 'World' in string at position 7
Found 'test' in string at position 19
'example' not found in string

解释

  1. **查找 "World"**:
  • `strstr(str, substr1)` 返回指向 `str` 中 `"World"` 首次出现位置的指针。

  • `ptr1 - str` 计算 `"World"` 在 `str` 中的起始位置。

  1. **查找 "test"**:
  • `strstr(str, substr2)` 返回指向 `str` 中 `"test"` 首次出现位置的指针。

  • `ptr2 - str` 计算 `"test"` 在 `str` 中的起始位置。

  1. **查找 "example"**:
  • `strstr(str, substr3)` 未找到 `"example"`,返回 `NULL`。

这个示例展示了如何使用 `strstr` 函数在一个字符串中查找子串,并输出子串的位置或未找到的信息。

相关推荐
lxmyzzs11 分钟前
【图像算法 - 23】工业应用:基于深度学习YOLO12与OpenCV的仪器仪表智能识别系统
人工智能·深度学习·opencv·算法·计算机视觉·图像算法·仪器仪表识别
Learn Beyond Limits14 分钟前
Multi-output Classification and Multi-label Classification|多输出分类和多标签分类
人工智能·深度学习·神经网络·算法·机器学习·分类·吴恩达
张较瘦_21 分钟前
[论文阅读] 软件工程 | GPS算法:用“路径摘要”当向导,软件模型检测从此告别“瞎找bug”
论文阅读·算法·bug
2401_858286111 小时前
OS26.【Linux】进程程序替换(下)
linux·运维·服务器·开发语言·算法·exec·进程
张同学的IT技术日记1 小时前
【奇妙的数据结构世界】用图像和代码对队列的使用进行透彻学习 | C++
算法
极客BIM工作室1 小时前
强化学习算法分类与介绍(含权重更新公式)
算法·分类·数据挖掘
KarrySmile2 小时前
Day8--HOT100--160. 相交链表,206. 反转链表,234. 回文链表,876. 链表的中间结点
数据结构·算法·链表·双指针·快慢指针·hot100·灵艾山茶府
luckycoding2 小时前
1424. 对角线遍历 II
算法·leetcode·职场和发展
CoovallyAIHub2 小时前
基于ICR损失与SVMLP数据集:小目标检测新突破,车牌检测准确率显著提升
深度学习·算法·计算机视觉
鲸鱼24012 小时前
贝叶斯笔记
人工智能·算法·机器学习