string.IndexOf(char value) 使用实例
时间: 2023-09-10 10:05:15 浏览: 44
以下是一个使用 `string.IndexOf(char value)` 方法的例子:
```csharp
string str = "Hello, world!";
int index = str.IndexOf('o');
if (index != -1)
{
Console.WriteLine($"\"o\" found at position {index}");
}
else
{
Console.WriteLine("\"o\" not found");
}
```
输出:
```
"o" found at position 4
```
在上面的例子中,我们使用 `IndexOf(char value)` 方法查找字符串中第一次出现字符 `'o'` 的位置,并将结果保存在 `index` 变量中。最后根据 `index` 的值输出查找结果。由于字符 `'o'` 确实出现在字符串中,因此输出字符串 `"o" found at position 4"`。如果要查找的字符不存在,`IndexOf()` 方法会返回 `-1`,我们可以根据这个返回值来判断查找是否成功。
相关问题
string.IndexOf(string value)使用例子
以下是一个使用 `string.IndexOf(string value)` 方法的例子:
```csharp
string str = "Hello, world!";
int index = str.IndexOf("world");
if (index != -1)
{
Console.WriteLine($"\"world\" found at position {index}");
}
else
{
Console.WriteLine("\"world\" not found");
}
```
输出:
```
"world" found at position 7
```
在上面的例子中,我们先定义了一个字符串 `str`,然后使用 `IndexOf(string value)` 方法查找字符串中第一次出现 `"world"` 的位置,并将结果保存在 `index` 变量中。最后根据 `index` 的值输出查找结果。由于 `"world"` 确实出现在字符串中,因此输出字符串 `"world" found at position 7"`。如果要查找的字符串不存在,`IndexOf()` 方法会返回 `-1`,我们可以根据这个返回值来判断查找是否成功。
c# string.indexof()
`string.IndexOf()` 是 C# 语言中用于查找字符串中第一次出现某个字符或者子字符串的位置的方法。该方法有多个重载形式,其中最常用的是接受一个 `string` 参数或者一个 `char` 参数的形式。
具体来说,`string.IndexOf(string value)` 方法会返回字符串中第一次出现 `value` 字符串的位置,如果没有找到则返回 -1。而 `string.IndexOf(char value)` 方法则会返回字符串中第一次出现 `value` 字符的位置。
此外,`string.IndexOf()` 还有一些其他重载形式,可以指定从字符串中的某个位置开始查找,或者指定查找的方式等等。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)