我有一个名为hello world的字符串

我需要把"world"换成" chsharp "

我用:

string.Replace("World", "csharp");

但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。

有没有办法避免字符串中的这种区分大小写的情况?替代方法?


当前回答

你可以使用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"
    }
}

其他回答

我推荐StringComparison。CurrentCultureIgnoreCase方法由ZZY / Gama Sharma提出。这是另一个可以用于LINQ的技术:

List<string> ItemsToRedact = new List<string> {"star", "citizen", "test", "universe"}; string Message =“就像每颗恒星都是独一无二的,但却造就了宇宙,你身上的光芒造就了你”; List<string> ReplacementList =消息。(' ')。Where(x => itemstoredata . contains (x. tolower ())).ToList(); foreach(替换列表中的变量) { Message = Message。替换(单词,“[已编辑]”); } Console.WriteLine(消息);

就像每个人都是独一无二的一样,你身上的光芒也造就了你

这段代码可以进一步提炼,但为了可读性,我将其分解了

另一种方法是使用StringComparison选项忽略String.Replace()中的大小写敏感性。CurrentCultureIgnoreCase

string.Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase)

扩展让我们的生活更简单:

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;
    }
}

下面的函数是从字符串集中删除所有匹配的单词(this)。作者:Ravikant Sonare。

private static void myfun()
{
    string mystring = "thiTHISThiss This THIS THis tThishiThiss. Box";
    var regex = new Regex("this", RegexOptions.IgnoreCase);
    mystring = regex.Replace(mystring, "");
    string[] str = mystring.Split(' ');
    for (int i = 0; i < str.Length; i++)
    {
        if (regex.IsMatch(str[i].ToString()))
        {
            mystring = mystring.Replace(str[i].ToString(), string.Empty);

        }
    }
    Console.WriteLine(mystring);
}

用Regex扩展Petrucio的答案。在搜索字符串上转义,并在Steve B的回答中建议转义匹配的组(和一些小的改变,我的口味):

public static class StringExtensions
{
    public static string ReplaceIgnoreCase(this string str, string from, string to)
    {
        return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
    }
}

这将产生以下预期结果:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe"));   // heLLo wOrld

然而,如果不执行转义,您将得到以下结果,这不是String的预期行为。替换是不区分大小写的:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe"));   // Hi heLLo Universe