c#获取字符串指定字符后面的
时间: 2023-09-02 19:07:43 浏览: 76
可以使用 C# 的 Substring() 方法和 IndexOf() 方法来获取字符串中某个字符后面的子串。例如,假设我们要获取字符串 str 中字符 ',' 后面的子串,代码如下:
```csharp
string str = "hello,world";
int index = str.IndexOf(',');
if (index >= 0)
{
string result = str.Substring(index + 1);
Console.WriteLine(result); // 输出 "world"
}
```
在这里,我们首先使用 IndexOf() 方法找到字符 ',' 的位置,如果存在则返回它的索引值,否则返回 -1。然后,我们使用 Substring() 方法获取从该索引位置后一位开始的子串,即为 ',' 后面的子串。最后,我们输出结果 "world"。
相关问题
C# 替换字符串指定位置字符
要替换字符串中的指定位置字符,可以使用 StringBuilder 类。以下是 C# 代码示例:
```csharp
string str = "hello world";
int index = 6; // 要替换的字符在字符串中的索引位置
char newChar = 'W'; // 新字符
StringBuilder sb = new StringBuilder(str);
sb[index] = newChar; // 替换字符
string newStr = sb.ToString();
Console.WriteLine(newStr); // 输出:hello World
```
在上面的示例中,我们首先创建了一个字符串 "hello world",然后指定要替换的字符的索引位置为 6(即字符 'w' 的位置),将要替换的字符设为大写的 'W'。接着,我们使用 StringBuilder 类的实例 sb 将字符串 str 转换成可编辑的字符串,然后使用索引操作符 [] 替换了指定位置的字符。最后,我们将 StringBuilder 对象转换回字符串类型,并将结果输出到控制台。
c# 字符串删除指定字符串
可以使用 C# 中的 Replace 方法来删除指定字符串,例如:
```csharp
string str = "hello world";
string toRemove = "world";
string result = str.Replace(toRemove, "");
```
这样就可以将字符串中的 "world" 删除,得到结果 "hello"。如果要删除多个指定字符串,可以依次调用 Replace 方法。