使用 strstr 函数来检查一个字符串是否包含 C 语言中的子字符串
使用 strcasestr 函数检查字符串是否包含子字符串
使用 strncpy 函数复制一个子字符串
本文将介绍几种在 C 语言中检查一个字符串是否包含给定子字符串的方法。
使用 strstr 函数来检查一个字符串是否包含 C 语言中的子字符串
strstr 函数是 C 标准库字符串工具的一部分,它被定义在
#include
#include
#include
const char *tmp = "This string literal is arbitrary";
int main(int argc, char *argv[]) {
char *ret;
ret = strstr(tmp, "literal");
if (ret)
printf("found substring at address %p\n", ret);
else
printf("no substring found!\n");
exit(EXIT_SUCCESS);
}
输出:
found substring at address 0x55edd2ecc014
使用 strcasestr 函数检查字符串是否包含子字符串
strcasestr 并不是标准库功能的一部分,但它是作为 GNU C 库的一个扩展来实现的,可以用 _GNU_SOURCE 宏定义来表示。定义后,我们就可以调用 strcasestr 函数来查找给定子字符串的首次出现。但请注意,这个函数会忽略两个字符串的大小写。
#define _GNU_SOURCE
#include
#include
#include
const char *tmp = "This string literal is arbitrary";
int main(int argc, char *argv[]) {
char *ret;
ret = strcasestr(tmp, "LITERAL");
if (ret)
printf("found substring at address %p\n", ret);
else
printf("no substring found!\n");
exit(EXIT_SUCCESS);
}
输出:
found substring at address 0x55edd2ecc014
使用 strncpy 函数复制一个子字符串
或者,可以使用 strncpy 函数将给定的子字符串复制到一个新的缓冲区。它需要三个参数,第一个参数是目标 char 指针,复制的子字符串将被存储在那里,第二个参数是源字符串,最后一个参数表示复制的第一个字节数。第二个参数是源字符串,最后一个参数表示最多复制的第一个字节数。请注意,如果在源字符串的第一个字节中没有找到空字节,那么目标字符串就不会以空结束。
#include
#include
#include
const char *tmp = "This string literal is arbitrary";
int main(int argc, char *argv[]) {
char *str = malloc(strlen(tmp));
printf("%s\n", strncpy(str, tmp, 4));
printf("%s\n", strncpy(str, tmp + 5, 10));
free(str);
exit(EXIT_SUCCESS);
}
输出:
This
string lit
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe