C# 查找字符在字符串位置
时间: 2023-09-08 21:13:00 浏览: 428
你可以使用C#的`IndexOf`方法来查找字符在字符串中的位置。这个方法会返回字符在字符串中第一次出现的索引位置,如果字符不存在于字符串中,则返回-1。以下是一个示例:
```csharp
string str = "Hello, World!";
char ch = 'o';
int index = str.IndexOf(ch);
Console.WriteLine("字符 '{0}' 在字符串中的索引位置是: {1}", ch, index);
```
输出结果将是:
```
字符 'o' 在字符串中的索引位置是: 4
```
你可以根据自己的需求使用这个方法来查找字符在字符串中的位置。
相关问题
C# 查找字符串
在 C# 中查找字符串可以使用 String 类的 IndexOf() 方法。此方法接受一个字符串参数,表示需要查找的子字符串,并返回该子字符串在原始字符串中第一次出现的索引。如果未找到该子字符串,则返回 -1。
例如,以下代码演示了在字符串中查找子字符串 "hello" 的示例:
```csharp
string str = "world, hello!";
int index = str.IndexOf("hello");
if (index != -1)
{
Console.WriteLine("子字符串 hello 在字符串中的位置为:{0}", index);
}
else
{
Console.WriteLine("未找到子字符串 hello");
}
```
输出结果为:子字符串 hello 在字符串中的位置为:7
c#查找指定字符串第一次出现的位置
你可以使用C#中的`IndexOf`方法来查找指定字符串第一次出现的位置。示例代码如下:
```c#
string str = "hello world";
string substr = "world";
int index = str.IndexOf(substr); // index的值为6
```
在上面的示例代码中,我们定义了一个字符串`str`和一个子字符串`substr`,然后使用`IndexOf`方法查找子字符串`substr`第一次出现的位置,并将结果存储在变量`index`中。注意,`IndexOf`方法区分大小写,如果想要忽略大小写,可以使用`IndexOf`方法的重载版本,并设置`StringComparison`参数为`StringComparison.OrdinalIgnoreCase`。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)