在C中查找数组的索引

时间:2016-12-02 20:43:02

标签: c arrays recursion indexing

我想写一个代码,这个代码可以让我找到一个拳头出现的位置,这是我到目前为止所得到的。如您所见,函数返回的实际上是值而不是索引。有没有办法找到它而不是简单地给出索引的初始值,如代号2?

char *recFirstPosition(char * source, int letter)
{

     if(*source == letter)
        return *source;

     if (*source =='\0')
      return 0;

     recFirstPosition(++source, letter);
}


char *recFirstPosition(char * source, int letter, int index)
{

     if(*(source+index) == letter)
        return index;

     if (*(source+index) =='\0')
      return 0;

     recFirstPosition(source, letter, ++index);
}

1 个答案:

答案 0 :(得分:0)

这是我认为可行的。请测试一下,因为我没有足够的时间来处理它 编辑:返回最后一次出现的位置,但应该足以让你使用。
Edit2:更新了函数,现在它适用于

#include <stdio.h>

char *recFirstPosition(const char *s, int c, char *find){
    if(s==NULL) return NULL;
    if(*s == '\0') return (c == '\0') ? (char*)s : find;
    if(*s == c) return (char*) s;
    return recFirstPosition(s + 1, c, *s == c ? (char*)s : find);
}


int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=recFirstPosition(str,'s', NULL);
  // Uncomment the while loop to get all instances positions  
  //while (pch!=NULL)
  //{
    printf ("found at %d\n",pch-str+1);
  //  pch=recFirstPosition(pch+1,'s',NULL);

  //}
  return 0;
}

输出 Looking for the 's' character in "This is a sample string"... found at 4

相关问题