C#String.IndexOf()方法

C# String.IndexOf( ) Method

C#中的String.IndexOf()方法用于查找此实例中首次出现的指定Unicode字符或字符串的从零开始的索引。

句法

语法如下-

1
public int IndexOf (string val);

上面的val是要查找的字符串。

现在让我们看一个例子-

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
public class Demo {
 public static void Main(String[] args) {
   string str1 ="Jacob";
   string str2 ="John";
   Console.WriteLine("String 1 ="+str1);
   Console.WriteLine("HashCode of String 1 ="+str1.GetHashCode());
   Console.WriteLine("Index of character 'o' is str1 =" + str1.IndexOf("o"));
   Console.WriteLine("
String 2 ="+str2);
   Console.WriteLine("HashCode of String 2 ="+str2.GetHashCode());
   Console.WriteLine("Index of character 'o' is str2 =" + str2.IndexOf("o"));
   bool res = str1.Contains(str2);
   if (res)
    Console.WriteLine("Found!");
   else
    Console.WriteLine("Not found!");
 }
}

输出量

这将产生以下输出-

1
2
3
4
5
6
7
String1=Jacob
HashCodeofString1=-790718923
Index of character 'o' is str1 = 3
String2=John
HashCodeofString2=-1505962600
Indexofcharacter'o'isstr2=1
Notfound!

现在让我们来看另一个例子-

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
public class Demo {
 public static void Main(String[] args) {
   string str1 ="Kevin";
   string str2 ="Evin";
   Console.WriteLine("String 1 ="+str1);
   Console.WriteLine("HashCode of String 1 ="+str1.GetHashCode());
   Console.WriteLine("Index of character 'k' in str1 =" + str1.IndexOf("k"));
   Console.WriteLine("
String 2 ="+str2);
   Console.WriteLine("HashCode of String 2 ="+str2.GetHashCode());
   Console.WriteLine("Index of character 'k' in str2 =" + str2.IndexOf("k"));
   bool res = str1.Contains(str2);
   if (res)
    Console.WriteLine("Found!");
   else
    Console.WriteLine("Not found!");
 }
}

输出量

这将产生以下输出-

1
2
3
4
5
6
7
String1=Kevin
HashCodeofString1=-768104063
Index of character 'k' in str1 = -1
String2=Evin
HashCodeofString2=1223510568
Indexofcharacter'k'instr2=-1
Notfound!