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

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

我用:

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

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

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


当前回答

你可以用微软。VisualBasic命名空间来查找这个帮助函数:

Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)

其他回答

您还可以尝试Regex类。

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

这样不行吗?我想象不出还有什么比这更快更简单的方法了。

public static class ExtensionMethodsString
{
    public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
    {
        string working = thisString;
        int index = working.IndexOf(oldValue, stringComparison);
        while (index != -1)
        {
            working = working.Remove(index, oldValue.Length);
            working = working.Insert(index, newValue);
            index = index + newValue.Length;
            index = working.IndexOf(oldValue, index, stringComparison);
        }
        return working;
    }
}

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

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

我推荐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)