2015-04-12 98 views
-4

我想返回一个没有整数或数组索引的字符串中的子字符串的指针。这是我的代码。我不知道如何让它发挥作用。C找到字符串中的子字符串与指针

/* 
* Return a pointer to the first character of the first occurrence of 
* <substr> in the given <string> or NULL if <substr> is not a substring 
* of <string>. 
* Note: An empty <substr> ("") matches *any* <string> at the <string>'s 
* start. 
***** 
* YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING. 
***** 
*/ 
char *find_substr(char *string, char* substr) { 

    char* first_occ = NULL; 

    while(*string) { 
     if(*string++ == *substr) { 
      if(first_occ == NULL){ 
       first_occ = string; 
      } 
      char const *a = substr; 
      while((*string++ == *++a) && (*a)); /*empty*/ 
      if(*a == '\0') 
       return first_occ; 
     } 
    } 
    return first_occ; 
} 
+1

请注明你的具体问题。 “不起作用,为我修复”不是一个具体问题。例如,请描述你的程序目前做错了什么,你如何试图解决这个问题以及你需要什么特定的帮助。 – kaylum

+0

我知道当一个空字符串作为substr传入时,它会返回null而不是字符串开头的指针。它也是当输入“bca”作为substr它匹配字符串“abccba” –

+0

可能重复[重新启动while循环在c中没有整数](http://stackoverflow.com/questions/29587005/restarting-while- loop-in-c-without-Integers) –

回答

0

如果substr是一个空字符串,首先您的代码不起作用。为此添加一个简单的测试。

第二:为什么你只保存首字符的第一个匹配?这会导致错误的指针返回find_substr("aab", "ab")

if(first_occ == NULL){ 
    first_occ = string; 
} 

您应该删除测试。

然后你检查其它字符,但你没有保存的string价值给它的匹配失败的情况下重置:

 char const *a = substr; 
     while((*string++ == *++a) && (*a)); /*empty*/ 
     if(*a == '\0') 
      return first_occ; 

这里是一个修正版本:

char *find_substr(char *string, char *substr) { 
    for (;;) { 
     if (*string == *substr) { 
      for (char *p1 = string, *p2 = substring;;) { 
       if (!*p2) 
        return string; 
       if (*p1++ != *p2++) 
        break; 
      } 
     } 
     if (!*string++) 
      break; 
    } 
    return NULL; 
} 
+0

在技术上'\ 0'是一个整数常量...我将删除这些,*不能使用整数*。 @Isaiah Scott:你明白这个答案吗? – chqrlie