2013-12-21 119 views
0

我正在尝试编写函数(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

+1

使用'strstr' .... –

+0

我的坏我应该包括,我试图避免这种方式! –

+0

你会如何知道是否返回任何内容?你不检查'findstring()'的返回码... – DaV

回答

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 

编辑:有错字。

+0

谢谢安德烈!我实际上是在没有strstr的情况下这样做的,但是我很感谢帮助我找到我的错误。 –

+1

-1。在这个答案中没有提到函数的返回值。 – haccks

+0

@哈哈,真的,谢谢你的纠正。 –

1

假设sourcelookup都是非空字符串,那么lenlookuplensource都是严格肯定的。

而且你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)所以该循环从未执行

顺便说一句,我强烈建议您编译所有警告和调试信息(例如gcc -Wall -g)和使用调试器(例如gdb)一步一步地运行并理解正在发生的事情。

+0

Thx!现在感觉很好! –

+0

+ 1.你的回答是合理的。我建议你看看OP的声明:*但是,当我运行它时,没有任何返回。*。 – haccks

0
  1. 你错过了
  2. 没有正确执行
  3. 比较基本的输入检查(如果源或查找是NULL,如果查找就是一个空字符串,如果有什么查找比源长,等等)
  4. 你的函数并不总是返回一个值(如果在源代码中找不到查找,它会返回什么?)。
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,博耶 - 穆尔和拉宾,卡普。

相关问题