C# 字符串删除特定字符:方法和示例
在 C# 中,你可以使用 'string.Replace()' 方法来删除字符串中的特定字符。该方法会将指定字符替换为指定的新字符或者删除它们。下面是一个示例:
string str = 'Hello, C#!';
char charToRemove = 'o';
string newStr = str.Replace(charToRemove.ToString(), '');
Console.WriteLine(newStr);
输出结果为:'Hell, C#!',其中的字符 'o' 被删除了。
如果你想删除多个字符,可以将 'string.Replace()' 方法多次调用来删除每个字符。另外,你也可以使用正则表达式来删除特定的字符。下面是一个使用正则表达式删除多个字符的示例:
using System.Text.RegularExpressions;
string str = 'Hello, C#!';
string charsToRemove = 'eo';
string newStr = Regex.Replace(str, '[' + Regex.Escape(charsToRemove) + ']', '');
Console.WriteLine(newStr);
输出结果为:'Hll, C#!',其中的字符 'e' 和 'o' 被删除了。
原文地址: https://www.cveoy.top/t/topic/qeSD 著作权归作者所有。请勿转载和采集!