我正在尝试编写一个函数(findString)来查明字符串是否存在于另一个字符串中。对于我的函数,第一个参数是搜索到的字符串,第二个参数是试图找到的字符串。
如果找到该字符串,则返回源字符串的位置。
我的书面代码如下:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
int findstring(char source[], char lookup[]){
int lensource, lenlookup;
lensource= strlen(source);
lenlookup = strlen(lookup);
int i;int j;
for(i=0; i>=lensource; ++i)
for (j=0; j>=lenlookup; ++j)
if (source[i]==lookup[j])
return i;
}
int main(){
findstring("Heyman","ey");
}
如果函数正常工作,则应返回索引2.
但是,当我运行它时,不会返回任何内容。我想问题是我的for循环或if语句的方法有问题。
我这样做而不使用strstr
答案 0 :(得分:2)
首先,有一个函数可以执行此操作,称为strstr
。
其次,你的循环写得不正确。它应该是:
for(i=0; i < lensource - lenlookup + 1; ++i) {
for (j=0; j<lenlookup; ++j)
if (source[i + j]!=lookup[j])
break;
if (j == lenlookup) return i + 1; // edit: had error
// note that return i feels more right, but
// op's spec seems to want i + 1
}
return -1; // no spec on return value for failure, but -1 seems reasonable
编辑:有错字。
答案 1 :(得分:1)
假设source
和lookup
都是非空字符串,则lenlookup
和lensource
都是严格正数。
您的for
循环从不执行,因为
for(i=0; i>=lensource; ++i) {
// do something
}
被理解为(并由编译器翻译):
i=0;
while(i>=lensource) {
// do something;
// at last
++i;
}
所以你理解初始测试i>=lensource
是假的(在开始i==0
但是lensource>0
)所以循环永远不会被执行
BTW我强烈建议使用所有警告和调试信息(例如gcc -Wall -g
)和使用调试器(例如gdb
)来编译代码,以便逐步运行它步骤并了解正在发生的事情。
答案 2 :(得分:0)
int findstring(char source[], char lookup[]){
// when either input is NULL
if(source==NULL||lookup==NULL)return -1;
int lensource, lenlookup;
lensource= strlen(source);
lenlookup = strlen(lookup);
// when lookup is an empty string
if(lenlookup==0)return 0;
// when lookup is longer than source
if(lenlookup>lensource)return -1;
int i;int j;
for(i=0; i<=lensource-lenlookup; ++i){
bool success = true;
for (j=0; j<=lenlookup; ++j){
if(lenlookup[j]!=lenlookup[i+j]){
success = false;
break;
}
}
if(success)return i;
}
return -1;
}
您可能还想查看其他更有效的算法,如KMP,boyer-moore和rabin-karp。