我是 C 语言新手,我遇到了这个问题。谁能帮我解答一下吗?
尝试编写一个有两个参数都是字符串类型的函数。返回值告诉你第一个字符串是否是第二个参数字符串的子字符串
最佳答案
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
bool contains_substring(const char *str1, const char *str2) {
if (strstr(str1, str2) != NULL) {
return true;
}
else {
return false;
}
}
int main() {
const char *str1 = "This is a test";//this is the string that you will be comparing against
const char *str2 = "test";//this is the substring you're searching for.
if (!contains_substring(str1, str2)) {
printf("No match found!\n");
}
else {
printf("String 1 contains String 2\n");
}
return 0;
}
注意:由于此示例使用 stdbool 作为 bool 类型,因此必须使用 C99 选项 -std=c99
使用 gcc 或 clang 等相关编译器进行编译,如下所示:
gcc inputfile.c -std=c99 -o 输出二进制文件名
当然,您可以通过如下定义 bool 来完全避免包含该库并使用额外的编译器选项(来自 here ):
typedef int bool;
#define false 0
#define true 1
关于c - 我需要有关 C 中字符串的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019471/