我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
当前回答
(编辑:没有意识到“裸链接”的问题,对不起)
从这里开始:
string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
似乎你不是第一个抱怨字符串不区分大小写的人。
其他回答
这样不行吗?我想象不出还有什么比这更快更简单的方法了。
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;
}
}
你可以用微软。VisualBasic命名空间来查找这个帮助函数:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
.Net Core有这个内置的方法: 替换(String, String, StringComparison) Doc。现在我们可以简单地写: “…”。替换("oldValue", "newValue", stringcompare . ordinalignorecase)
我的这个方法可以忽略大小写以及只选择整个单词
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);
}