C#移除字符串中子串
有多种方法可以从字符串中移除子串,以下是其中一些常用的方法:
- 使用 Replace 方法:
string str = "Hello World!";
string subStr = "llo";
string result = str.Replace(subStr, "");
// result = "He World!"
- 使用 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!"
}
- 使用正则表达式:
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);
``
原文地址: http://www.cveoy.top/t/topic/cn2g 著作权归作者所有。请勿转载和采集!