假设这些是实际上字符串而不是没有字符串终止符的字符数组,这很容易做到。
你说你没有世界上w的索引,所以这是一个问题:
strcmp (b, a+index)
或:
strcmp (b, &(a[index]))
取决于您认为哪个更好读(底层代码应该几乎相同)。
例如,看看这个程序:
#include <stdio.h>
#include <string.h>
int main (void) {
char *str1 = "world";
char *str2 = "hello world";
for (size_t i = 0; i < strlen (str2); i++)
printf ("%s on match '%s' with '%s'\n",
strcmp (str1, str2+i) ? "No " : "Yes",
str1, str2+i);
return 0;
}
哪个输出:
No on match 'world' with 'hello world'
No on match 'world' with 'ello world'
No on match 'world' with 'llo world'
No on match 'world' with 'lo world'
No on match 'world' with 'o world'
No on match 'world' with ' world'
Yes on match 'world' with 'world'
No on match 'world' with 'orld'
No on match 'world' with 'rld'
No on match 'world' with 'ld'
No on match 'world' with 'd'
无论它们是字符串文字还是正确终止的字符数组都没有区别。将两个声明行替换为:
char str1[] = {'w','o','r','l','d','\0'};
char str2[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
同样有效。
如果它们没有正确终止,str... 调用就不是真正适合使用的调用。