使用C#扩展方法定义一个类似Indexof 的字符串查找功能

  
  使用Unity3d开发VR有几个月了,据说string的 Indexof 方法要尽量避免频繁使用,在把自己的框架移植成Unity3d的过程中,恰巧有个地方需要频繁调用,于是突发奇想,用了下面的办法一定程度替代Indexof方法的使用。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public static class SDExtension
{
    public static bool HasSub(this string target, string check)
    {
        StringBuilder sb = new StringBuilder(target);
        int m = sb.Length;
        sb = sb.Replace(check, check + "1");
        return (m != sb.Length);
    }

}


  利用StringBuilder类高效生成字符串的特性,将要查找的子串在StringBuilder中替换成一个新串,如果替换后的字符串长度多出指定数量,则说明原字符串中包含有子串,从而达到判断字符串是否包含一个子串的作用(str.IndexOf("sss") != -1)。同时也避免了频繁调用string引起的性能影响,但缺点是不能像IndexOf一样返回子串在原字符串里的起始索引号。由于还是一个尝试,其可用性还需要验证,有不对的或者有更好的方案欢迎跟帖。

猜你喜欢

转载自fis.iteye.com/blog/2316340