.net - 在不使用Regex的情况下,.Net中是否存在不区分大小写的字符串替换?

标签 .net string replace

我最近不得不在.net中执行一些字符串替换,并且发现自己为此目的开发了一个正则表达式替换功能。使它正常工作后,我禁不住想。我必须缺少一个内置的不区分大小写的替换操作,但我没有呢?

当然,当还有很多其他字符串操作支持不区分大小写的比较时,例如;

var compareStrings  = String.Compare("a", "b", blIgnoreCase);
var equalStrings    = String.Equals("a", "b", StringComparison.CurrentCultureIgnoreCase);

那么必须有一个等效的内置替代品吗?

最佳答案

在这里的评论中找到一个:http://www.codeproject.com/Messages/1835929/this-one-is-even-faster-and-more-flexible-modified.aspx

static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
{
     return Replace(original, pattern, replacement, comparisonType, -1);
}

static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType, int stringBuilderInitialSize)
{
     if (original == null)
     {
         return null;
     }

     if (String.IsNullOrEmpty(pattern))
     {
         return original;
     }


     int posCurrent = 0;
     int lenPattern = pattern.Length;
     int idxNext = original.IndexOf(pattern, comparisonType);
     StringBuilder result = new StringBuilder(stringBuilderInitialSize < 0 ? Math.Min(4096, original.Length) : stringBuilderInitialSize);

     while (idxNext >= 0)
     {
        result.Append(original, posCurrent, idxNext - posCurrent);
        result.Append(replacement);

        posCurrent = idxNext + lenPattern;

        idxNext = original.IndexOf(pattern, posCurrent, comparisonType);
      }

      result.Append(original, posCurrent, original.Length - posCurrent);

      return result.ToString();
}

应该是最快的,但是我还没有检查。

否则,您应该执行Simon的建议并使用VisualBasic Replace函数。由于不区分大小写,我经常这样做。
string s = "SoftWare";
s = Microsoft.VisualBasic.Strings.Replace(s, "software", "hardware", 1, -1, Constants.vbTextCompare);

您必须添加对Microsoft.VisualBasic dll的引用。

关于.net - 在不使用Regex的情况下,.Net中是否存在不区分大小写的字符串替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5549426/

相关文章:

.net - 如何构建共享项目

.net - BackgroundWorker 和 Thread 的区别?

php - 使用 PHP 代码替换 MYSQL 字符串

text - 合并两个unicode文本文件的非空行,使用windows批处理

从A点到B点的mysql正则表达式

c# - 附加和更新 bool 值或 int 并不总是有效

.net - 使用 jQuery 将 JSON 对象发送到 asp.net WebMethod 时出错

python - 将通过套接字传输的字符串数据快速转换为 Python 中的对象

java - 将字符串拆分为几个两个字符串

c++ - 如何在不删除任何字符的情况下将字符从字符串中的某个位置移动到它的最前面?