用户给我们更长的字符串 s
和更短的字符串 t
。
如果t
在s
中,则字符串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 值 0
或 1
:
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/