C#实现String.IndexOf功能 查找字符串

class  Program
 2      {
 3        static void Main(string[] args)
 4        {
 5            string str1 = "";
 6            string str2 = "";
 7
 8            Console.WriteLine(str1.IndexOf(str2));
 9            Console.WriteLine(StringIndexOf(str1, str2));
10
11            Console.ReadKey();
12        }

13
14        /// <summary>
15        /// 实现字符串的IndexOf 功能 
16        /// </summary>
17        /// <param name="strMain"></param>
18        /// <param name="strExtre"></param>
19        /// <returns></returns>

20        static int StringIndexOf(string strMain, string strExtre)
21        {
22            if (strMain == null || strExtre == null)
23                throw new Exception("String cannot be null.");
24            if (strExtre.Length == 0return 0;
25            if (strExtre.Length > strMain.Length) return -1;
26
27            //返回值
28            int index = -1;
29            //获取附加字符串首字符 
30            char c = strExtre[0];
31            //在主字符串中搜索首字符
32            for (int i = 0; i < strMain.Length; i++)
33            {
34                //不匹配的话继续搜索
35                if (false == strMain[i].Equals(c)) continue;
36
37                int Length = 1;
38                //从次首字符开始比较
39                for (int j = 1; j < strExtre.Length; j++)
40                {
41                    if ((i + j) >= strMain.Length) break;
42                    if (false == strMain[i + j].Equals(strExtre[j])) break;
43                    Length++;
44                }

45                //条件匹配即退出
46                if (Length == strExtre.Length)
47                {
48                    index = i;
49                    break;
50                }

51            }

52
53            return index;
54        }

55    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值