合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。💪🏻
C
语言 判断字符串S2
是否在字符串S1
中
c
#include <stdio.h> // 引入标准输入输出库,用于使用 printf 等函数
#include <string.h> // 引入字符串处理库,用于使用 strstr 等函数
int main() {
const char *S1 = "Hello, world!"; // 定义字符串 S1,内容为 "Hello, world!"
const char *S2 = "world"; // 定义字符串 S2,内容为 "world"
char *p; // 定义一个字符指针 p,用于存储 strstr 的返回值
// 使用 strstr 函数在 S1 中查找 S2
// 如果 S2 是 S1 的子串,p 指向 S2 在 S1 中首次出现的位置
// 如果 S2 不是 S1 的子串,p 为 NULL
if ((p = strstr(S1, S2)) == NULL) {
// 如果 p 为 NULL,说明 S2 不在 S1 中
printf("'%s' not found in '%s'\n", S2, S1); // 输出未找到的信息
} else {
// 如果 p 不为 NULL,说明 S2 是 S1 的子串
// 计算 S2 在 S1 中的位置(p - S1 表示指针偏移量)
printf("'%s' found in '%s' at position: %ld\n", S2, S1, p - S1); // 输出找到的位置
}
return 0; // 程序正常结束
}
