Nik*_*kar 1 c# string substring
我想在不使用任何字符串方法(包括indexof)的情况下找到字符串中子字符串的位置.我尝试了很多次却失败了.有人会告诉我怎么做C#?我们可以使用.Length运算符.
对不起..以为这对我来说很有趣,所以......
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17405 次 |
| 最近记录: |