c - 我需要有关 C 中字符串的帮助

标签 c string function

我是 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

引用 http://en.cppreference.com/w/c/string/byte/strstr

关于c - 我需要有关 C 中字符串的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019471/

相关文章:

c - glVertexAttribPointer、交错元素和性能/缓存友好性

c - C 中的结构体和指针

r - 从函数调用将变量传递给 ggpubr

c++ - 为什么这个程序显示 "unreachable code"警告?我该如何抑制它?

javascript - 依次调用 Angular2 函数

c - 指向函数错误的指针

android - 内核 c 多重函数定义错误

引号中的 Python 变量值

c++ - 将字符串转换为二进制的最快方法?

javascript - 从 Javascript 中的字符串中获取最后一个单词