c - 一根绳子位于另一根绳子内吗?

标签 c string function

用户给我们更长的字符串 s 和更短的字符串 t

如果ts中,则字符串t中的符号?可以作为任意字符使用, 显示一条消息。

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

int isit(char*,char*,int);
int main()
{
    char s[20],t[20];
    int k,i,fir;
    puts("Enter first string");
    gets(s);
    puts("Enter second string");
    gets(t);

    k=strlen(s)-strlen(t);

    for(i=0;i<=k;i++){
        fir=i;
        if(isit(s,t,fir)==1){
            printf("It's in there");
            return 1;
        }
    }

}
int isit(char*s,char*t,int fir){
    int i;
    for(i=fir;i<i+strlen(t)-1;i++)
        if(t[i]!=s[i] && t[i]!='?')
            return -1;
    return 1;
}

最佳答案

除其他问题外,函数 isit 没有为 t 使用正确的索引。用指针编写会简单得多,并且应该返回 bool 值 01:

int isit(const char *s, const char *t, int first) {
    for (s += first; *t; s++, t++) {
        if (!*s || (*s != *t && *t != '?'))
            return 0;
    }
    return 1;
}

同时使用更一致的间距和更明确的变量名:如果函数很短且名称是惯用的,则 1 个字母的局部变量名是可以的(i 用于索引,s 表示 char *...),但愚蠢的缩写不是(fir 表示 first)。函数名 isit 没有关于它做什么的信息!事实上,您甚至不需要函数,您可以为此使用标准函数:

strncmp(s + first, t, strlen(t)) == 0

编辑:但正如 M.Oehm 指出的那样,这不会处理 ? 通配符。

关于c - 一根绳子位于另一根绳子内吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33450239/

相关文章:

c - 如何在 C 和 CUDA 中通过修改后的 Gram-Schmidt 方法进行 QR 分解

c - 在系统 verilog 代码中集成 fftw C 函数调用

swift - 如何快速处理大字符串?

c - 使用 sscanf 读取带空格的字符串

function - 一流功能的缺点

php - 如何将数组作为多个参数传递给函数?

c - g++中的多重定义?

C unsigned long 转换未正确添加

Python复杂的正则表达式字符串扩展

iphone - 如何检查 objective-c 中的变量是否每秒或更少发生变化?