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

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

我用:

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

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

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


当前回答

您还可以尝试Regex类。

var regex = new regex ("camel", RegexOptions. var regex = new regex。IgnoreCase); var newSentence =正则表达式。替换(句子,“马”);

其他回答

.Net Core有这个内置的方法: 替换(String, String, StringComparison) Doc。现在我们可以简单地写: “…”。替换("oldValue", "newValue", stringcompare . ordinalignorecase)

你可以使用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(消息);

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

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

(编辑:没有意识到“裸链接”的问题,对不起)

从这里开始:

string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);

似乎你不是第一个抱怨字符串不区分大小写的人。

我更喜欢这个- "Hello World". tolower()。Replace("world", " chsharp ");