C# 移除字符串中子串:多种方法解析及示例

在 C# 中,有多种方法可以从字符串中移除子字符串,以下是其中一些常用的方法:

1. 使用 Replace 方法:

string str = 'Hello World!';
string subStr = 'llo';
string result = str.Replace(subStr, '');
// result = 'He World!'

2. 使用 Remove 方法:

string str = 'Hello World!';
string subStr = 'llo';
int index = str.IndexOf(subStr);
if (index >= 0)
{
    string result = str.Remove(index, subStr.Length);
    // result = 'He World!'
}

3. 使用正则表达式:

using System.Text.RegularExpressions;

string str = 'Hello World!';
string subStr = 'llo';
string pattern = Regex.Escape(subStr);
string result = Regex.Replace(str, pattern, '', RegexOptions.IgnoreCase);
// result = 'He World!'

需要注意的是,以上方法都是不区分大小写的。如果需要区分大小写,需要将相应的方法的参数调整一下。例如,使用 Replace 方法时可以这样:

string result = str.Replace(subStr, '', StringComparison.Ordinal);
C# 移除字符串中子串:多种方法解析及示例

原文地址: https://www.cveoy.top/t/topic/nuHs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录