溫馨提示×

c# string如何查找子串位置

c#
小樊
152
2024-10-18 18:39:30
欄目: 編程語言

在C#中,你可以使用string類的IndexOf方法來查找子串的位置。這個方法返回子串在字符串中首次出現的索引,如果沒有找到子串,則返回-1。

下面是一個示例代碼:

string str = "Hello, world!";
string subStr = "world";

int index = str.IndexOf(subStr);

if (index != -1)
{
    Console.WriteLine($"子串 \"{subStr}\" 在字符串 \"{str}\" 中的位置是: {index}");
}
else
{
    Console.WriteLine($"子串 \"{subStr}\" 在字符串 \"{str}\" 中未找到");
}

在這個例子中,IndexOf方法返回了子串"world"在字符串"Hello, world!"中首次出現的位置,即7。因此,控制臺輸出了“子串 ‘world’ 在字符串 ‘Hello, world!’ 中的位置是: 7”。

你還可以使用IndexOf方法的其他重載版本來查找子串在字符串中所有出現的位置。例如,IndexOf(string value, int startIndex)方法從指定的起始索引開始查找子串。

int index = str.IndexOf(subStr, 7); // 從索引7開始查找子串

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女