You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求C#递归函数实现数组中字符串索引查找(禁用IndexOf方法)

C#递归查找数组中指定字符串的索引(禁用IndexOf)

没问题,我来帮你搞定这个递归查找的需求!咱们可以通过递归跟踪当前检查的索引来实现,完全不用依赖IndexOf方法。

实现思路

递归的核心是拆解问题:每次只检查数组的一个元素,要么找到匹配项返回当前索引,要么继续递归检查下一个元素,直到遍历完整个数组(此时返回-1表示没找到目标)。为了让调用方更友好,我们可以用一个公共函数封装递归的起始逻辑,让调用者不用手动传初始索引。

完整代码实现

using System;

public class StringFinder
{
    // 对外暴露的公共方法,调用方只需传入数组和目标字符串
    public static int FindStringIndex(string[] array, string target)
    {
        // 从索引0开始启动递归
        return FindStringIndexRecursive(array, target, 0);
    }

    // 私有递归辅助方法,负责核心查找逻辑
    private static int FindStringIndexRecursive(string[] array, string target, int currentIndex)
    {
        // 基准情况:当前索引超出数组长度,说明遍历完了还没找到,返回-1
        if (currentIndex >= array.Length)
        {
            return -1;
        }

        // 比较当前元素和目标字符串,这里用Ordinal匹配保证精确性
        if (string.Equals(array[currentIndex], target, StringComparison.Ordinal))
        {
            return currentIndex;
        }

        // 递归调用,检查下一个索引
        return FindStringIndexRecursive(array, target, currentIndex + 1);
    }

    // 测试示例
    public static void Main()
    {
        string[] testArray = { "Hello", "How are you", "Good Bye" };
        int result = FindStringIndex(testArray, "How are you");
        Console.WriteLine(result); // 输出:1

        // 测试没找到的情况
        int notFoundResult = FindStringIndex(testArray, "Hi");
        Console.WriteLine(notFoundResult); // 输出:-1
    }
}

代码说明

  • 公共方法FindStringIndex:作为入口,帮调用者初始化递归的起始索引为0,简化调用体验;
  • 递归方法FindStringIndexRecursive:
    • 首先处理递归的终止条件:如果currentIndex超过数组长度,直接返回-1;
    • 用string.Equals做字符串比较,指定StringComparison.Ordinal可以避免因系统文化差异导致的匹配问题,保证精确匹配;
    • 如果当前元素不匹配,就递归调用自己,索引加1,继续检查下一个元素;
  • 边界情况处理:已经覆盖了数组为空、目标不存在、目标在数组首尾等情况。

调用示例

就像你给出的例子,调用FindStringIndex(new string[] { "Hello", "How are you", "Good Bye" }, "How are you")会直接返回1,完全符合需求。

内容的提问来源于stack exchange,提问作者Suren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:25:24