本文介绍了如何找到字符串的子串,而不在C#中使用IndexOf方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到一个子字符串中的位置(如果存在),而不使用任何字符串的方法,包括的indexOf。我尝试了这么多时间,但是失败了。会有人告诉我如何在C#中吗?我们可以用。长度操作符。
I want to find the position of a substring in a string if present without using any string method including indexof. I tried so much times but failed. Will anybody tell me how to do in C#? We can use .Length operator.
推荐答案
抱歉..认为这将是一个有趣的练习我,所以...
Sorry.. thought this would be a fun exercise for me, so...
class Program
{
static void Main(string[] args)
{
string str = "abcdefg";
string substr = "cde";
int index = IndexOf(str, substr);
Console.WriteLine(index);
Console.ReadLine();
}
private static int IndexOf(string str, string substr)
{
bool match;
for (int i = 0; i < str.Length - substr.Length + 1; ++i)
{
match = true;
for (int j = 0; j < substr.Length; ++j)
{
if (str[i + j] != substr[j])
{
match = false;
break;
}
}
if (match) return i;
}
return -1;
}
}
这篇关于如何找到字符串的子串,而不在C#中使用IndexOf方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!