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

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

我用:

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

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

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


当前回答

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

其他回答

我的这个方法可以忽略大小写以及只选择整个单词

public static string Replace(this string s, string word, string by, StringComparison stringComparison, bool WholeWord)
{
    s = s + " ";
    int wordSt;
    StringBuilder sb = new StringBuilder();
    while (s.IndexOf(word, stringComparison) > -1)
    {
        wordSt = s.IndexOf(word, stringComparison);
        if (!WholeWord || ((wordSt == 0 || !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt - 1, 1)))) && !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt + word.Length, 1)))))
        {
            sb.Append(s.Substring(0, wordSt) + by);
        }
        else
        {
            sb.Append(s.Substring(0, wordSt + word.Length));
        }
        s = s.Substring(wordSt + word.Length);
    }
    sb.Append(s);
    return sb.ToString().Substring(0, sb.Length - 1);
}

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

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

很多使用Regex的建议。如果没有它,这个扩展方法如何:

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

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

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

您还可以尝试Regex类。

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