C# 中的 String.IndexOf() 方法用於查找指定 Unicode 字符或字符串在此實例中第一次出現的從零開始的索引。
用法
語法如下 -
public int IndexOf (string val);
上麵, val 是要查找的字符串。
示例
現在讓我們看一個例子 -
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("\nString 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!");
}
}
輸出
這將產生以下輸出 -
String 1 = Jacob HashCode of String 1 = -790718923 Index of character 'o' is str1 = 3 String 2 = John HashCode of String 2 = -1505962600 Index of character 'o' is str2 =1 Not found!
示例
現在讓我們看另一個例子 -
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("\nString 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!");
}
}
輸出
這將產生以下輸出 -
String 1 = Kevin HashCode of String 1 = -768104063 Index of character 'k' in str1 = -1 String 2 = Evin HashCode of String 2 = 1223510568 Index of character 'k' in str2 =-1 Not found!
相關用法
- C# String.IndexOf()方法用法及代碼示例
- C# String.Insert()用法及代碼示例
- C# String.IsNullOrEmpty()用法及代碼示例
- C# String.IsNormalized用法及代碼示例
- C# String.ToUpperInvariant用法及代碼示例
- C# String.ToLowerInvariant用法及代碼示例
- C# String.ToCharArray()用法及代碼示例
- C# String.Copy()用法及代碼示例
- C# String.Clone()用法及代碼示例
- C# String.Split()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# String.Format()函數用法及代碼示例
- C# String.CopyTo()用法及代碼示例
- C# String.Compare()用法及代碼示例
- C# String.Format()方法用法及代碼示例
- C# StringBuilder.ToString用法及代碼示例
- C# String ToString()用法及代碼示例
- C# String Contains()用法及代碼示例
- C# String ToCharArray()用法及代碼示例
- C# String IndexOf()用法及代碼示例
注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 C# String.IndexOf() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。