我應該用 C 撰寫一個程式來檢查給定的子字串是否存在于給定的字串中。我寫的代碼在下面,但它不起作用。誰能告訴我問題出在哪里?
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[30]="the test string";
char sbstr[30]="test";
char strcp[30];
int len = strlen(str);
int i=0;
int p=0;
while(i<len)
{
while (str[i] != '\0' && str[i] != ' ')
{
strcp[i] = str[i];
i;
}
strcp[i] = '\0';
p = strcmp(sbstr, strcp);
if (p==0)
{
printf("exist");
break;
}
i;
}
}
uj5u.com熱心網友回復:
對于陣列 strcp
char strcp[30];
你需要支持一個單獨的索引。
就像是
int j = 0;
while (str[i] != '\0' && str[i] != ' ')
{
strcp[j ] = str[i ];
}
strcp[j] = '\0';
請注意,有strstr可用于執行任務的標準 C 函式。
uj5u.com熱心網友回復:
我知道你已經接受了一個答案,但這里有一種更有效的方法來進行子字串比較,它不涉及在每次迭代中制作候選子字串的副本。
char str[30]="the test string";
char sbstr[30]="test";
int len = strlen(str);
int sublen = strlen(sbstr);
int found = 0;
int i = 0; // starting index in str to start comparing on
while (!found && sublen <= len) {
found = 1;
// found = !strncmp(str i, sbstr, sublen);
for (int j = 0; j < sublen; j ) {
if (str[i j] != sbstr[j]) {
found = 0;
break;
}
}
if (!found) {
i ;
len--;
}
}
if (found) {
printf("Exists starting at index %d\n", i);
}
如果你真的想成為硬核,有一些眾所周知的演算法,比如Boyer-Moore 字串搜索演算法,它可以通過使用表查找方案 IIRC 來更快地搜索。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392773.html
