简单实现字符串查找算法
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始毫秒数"+DateTime.Now.ToString("fff"));
int i= MyIndexOf("aaabbbccddeeass","eeass");
Console.WriteLine(i);
Console.WriteLine("结束毫秒数"+DateTime.Now.ToString("fff"));
}
/// <summary>
/// 返回源字符串里面是否包含子字符串
/// </summary>
/// <param name="resorce">源字符串</param>
/// <param name="str">字符串</param>
/// <param name="ignoreCase">是否忽略大小写,true忽略大小写,false不忽略大小写,默认忽略大小写</param>
/// <returns></returns>
private static int MyIndexOf(string resorce, string str,bool ignoreCase=true)
{
if (string.IsNullOrEmpty(str)|| string.IsNullOrEmpty(resorce))
{
throw new Exception("字符串不能是null或者空");
}
//如果子字符串比源字符串都长,那么源字符串肯定不包含子字符
if (resorce.Length<str.Length)
{
return -1;
}
if (ignoreCase)
{
resorce = resorce.ToUpper();
str = str.ToUpper();
}
int count = 0; // 记录匹配次数,匹配次数与子字符串次数有关
int index = -1; // 记录返回字符串的下标
int temp = -1; // 使用一个临时变量记录从哪个字符串的下标开始匹配
for (int i=0;i< resorce.Length;i++)
{
index = i;
temp = i; ;
for (int j=0;j<str.Length;j++)
{
/**
* 如果匹配字符相等,那么源字符串和字符串分别往后面移动
* 如果其中有一次匹配不成功,那么就直接把结果进行清空
* 如果匹配次数等于字符串的长度,那么就将记录的下标进行返回
* **/
if (resorce[temp] == str[j])
{
count++;
if (count == str.Length)
{
return i; //直接结束查找
}
}
else
{
count=0; //只要发现不相等就退出
index = -1;
break;
}
temp++;
}
}
/*没有找到直接返回-1*/
return -1;
}
}
改后的暴力版本
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始毫秒数"+DateTime.Now.ToString("fff"));
int i= MyIndexOf("aaabbbccddeeass","eeass");
Console.WriteLine(i);
Console.WriteLine("结束毫秒数"+DateTime.Now.ToString("fff"));
}
/// <summary>
/// 返回源字符串里面是否包含子字符串
/// </summary>
/// <param name="resorce">源字符串</param>
/// <param name="str">字符串</param>
/// <param name="ignoreCase">是否忽略大小写,true忽略大小写,false不忽略大小写,默认忽略大小写</param>
/// <returns></returns>
private static int MyIndexOf(string resorce, string str,bool ignoreCase=true)
{
if (string.IsNullOrEmpty(str)|| string.IsNullOrEmpty(resorce))
{
throw new Exception("字符串不能是null或者空");
}
//如果子字符串比源字符串都长,那么源字符串肯定不包含子字符
if (resorce.Length<str.Length)
{
return -1;
}
if (ignoreCase)
{
resorce = resorce.ToUpper();
str = str.ToUpper();
}
int j = 0;
int i = 0;
//上面两个循环好理解,但是写起来太多了,稍微改了下
while (i <resorce.Length &&j<str.Length)
{
/*一旦有一个相等,两个字符串的下标都往后面移动一位*/
if (resorce[i] == str[j])
{
i++; //主串的下标
j++;//字串的下标
if (j==str.Length)
{
return i - j;//i-j就是首位匹配的下标
}
}
/* 一旦不相等,首先清空字串的下标设置为零(j=0),主串的下标要回到i-j的位置,上一位已经比较过了所以要(i-j+1)*/
else
{
i = i - j + 1;
j = 0;
}
}
/*找不到直接返回-1*/
return -1;
}
}