c - C中的字符串中存在子字符串

#include <stdio.h>
#include <string.h>

int main()
{
    char str1[80] = "downtown", str2[20] = "town";
    
    int len1 = 0, len2 = 0, i, j, count;

    len1 = strlen(str1);
    len2 = strlen(str2);

    for (i = 0; i <= len1 - len2; i++) { 
        for (j = i; j < i + len2; j++) {
            count = 1;
            if (str1[j] != str2[j - i]) {
                count = 0;
                break;
            }
        }
        if (count == 1) {
            break;
        }
    }
    if (count == 1) {
        printf("True");
    } else {
        printf("False");
    }
}

在上面的代码中,我试图在不使用字符串函数的情况下解决这个问题,strlen() 可以用简单的 while 循环代替。有没有其他检查连续字符的方法,比如首先检查字符是否在字符串中,以及 i 索引是否在下一个位置而不是随机出现在字符串中。

最佳答案

这是一种使用函数的非常简洁的方法。它假定 strsub是正确的 C 字符串并返回指向第一个匹配项和 NULL 的指针如果没有匹配。

char *substr(const char *str, const char *sub) {
    if (!*sub)
        return str; // Empty string is substring of all strings

    while (*str) {
        const char *sub1 = sub;
        const char *str1 = str;
        while (*str1++ == *sub1++) {
            if (!*sub1)
                return (char *)str;
        }
        str++;
    }
    return NULL;
}

此函数与标准函数相同 strstr() ,存在于 C 标准库中并在 <string.h> 中声明.

https://stackoverflow.com/questions/68816324/

相关文章:

regex - Linux 或 Vim : How to find and replace matc

python - 如何统计数字的总设置位数

javascript - 在 react.js 中加载图像时如何使用 OnLoad 显示加载器

vue.js - 如何使用 Nuxt 中间件重定向到外部站点?

python - 将重复列名列表和值列表转换为数据框

java - 包 io.swagger.v3.oas.annotations.media 不存在 (

f# - 在 F# 属性中使用 lazy 是否会阻止在不应该计算代码时计算代码?

r - 如何根据数据框名称中的单个字符在数据框中添加新列?

r - 导出多个匹配模式

postgresql - JSON 与 JSONB Postgresql