C#递归函数返回数组中字符串的索引(没有IndexOf函数)

时间:2018-01-09 10:00:42

标签: c# recursion

例如

find( new string[] { "Hello", "How are you", "Good Bye" }, "How are you" )

如果我运行此方法,我将输出1。

请求帮助我。谢谢。

1 个答案:

答案 0 :(得分:2)

如果您对递归感兴趣,并希望返回索引(-1如果找不到这样的toFind字符串),您可以尝试这样的事情:< / p>

 private static int find(string[] array, string toFind, int startFrom = 0) {
   if (startFrom >= array.Length)        // The array has been scanned up, no match found
     return -1;
   else if (array[startFrom] == toFind)  // match 
     return startFrom;
   else                                  // recursion check of the next item
     return find(array, toFind, startFrom + 1); 
 } 

...

 int test = find( new string[] { "Hello", "How are you", "Good Bye" }, 
                 "How are you" );