我有一个名为"hello world“的字符串
我需要把"world“改成"csharp”
为此,我使用:
string.Replace("World", "csharp");
但是结果是,我没有把字符串替换掉。原因是区分大小写。原始字符串包含"World“,而我正在尝试替换"world”。
有没有办法避免在string.Replace方法中区分大小写?
发布于 2011-06-08 16:19:29
您可以使用Regex并执行不区分大小写的替换:
class Program
{
static void Main()
{
string input = "hello WoRlD";
string result =
Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
Console.WriteLine(result); // prints "hello csharp"
}
}
发布于 2016-02-26 14:17:27
很多使用正则表达式的建议。这个不带它的扩展方法怎么样:
public static string Replace(this string str, string old, string @new, StringComparison comparison)
{
@new = @new ?? "";
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(@new, comparison))
return str;
int foundAt = 0;
while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
{
str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
foundAt += @new.Length;
}
return str;
}
发布于 2013-10-13 08:40:40
扩展让我们的生活更轻松:
static public class StringExtensions
{
static public string ReplaceInsensitive(this string str, string from, string to)
{
str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
return str;
}
}
https://stackoverflow.com/questions/6275980
复制相似问题