我最近不得不在.net中执行一些字符串替换,并发现自己为此目的开发了一个正则表达式替换函数。在开始工作之后,我忍不住想到.Net中必须有一个内置的不区分大小写的替换操作,我不知道了吗?
当有许多其他字符串操作支持不区分大小写的比较时,例如;
var compareStrings = String.Compare("a", "b", blIgnoreCase);
var equalStrings = String.Equals("a", "b", StringComparison.CurrentCultureIgnoreCase);
那么必须有一个内置的等效替换?
答案 0 :(得分:23)
在这里的评论中找到一个: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的引用。
答案 1 :(得分:15)
这不理想,但您可以导入Microsoft.VisualBasic
并使用Strings.Replace
执行此操作。否则我认为这是自己滚动或坚持使用正则表达式的情况。
答案 2 :(得分:4)
这是一种扩展方法。不知道我在哪里找到它。
public static class StringExtensions
{
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
}
答案 3 :(得分:2)
这是rboarman's answer above的VB.NET改编,必须检查空字符串和空字符串以避免无限循环。
Public Function Replace(ByVal originalString As String,
ByVal oldValue As String,
ByVal newValue As String,
ByVal comparisonType As StringComparison) As String
If Not String.IsNullOrEmpty(originalString) AndAlso
Not String.IsNullOrEmpty(oldValue) AndAlso
newValue IsNot Nothing Then
Dim startIndex As Int32
Do While True
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType)
If startIndex = -1 Then Exit Do
originalString = originalString.Substring(0, startIndex) & newValue &
originalString.Substring(startIndex + oldValue.Length)
startIndex += newValue.Length
Loop
End If
Return originalString
End Function
答案 4 :(得分:1)
我的2美分:
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
if (originalString == null)
return null;
if (oldValue == null)
throw new ArgumentNullException("oldValue");
if (oldValue == string.Empty)
return originalString;
if (newValue == null)
throw new ArgumentNullException("newValue");
const int indexNotFound = -1;
int startIndex = 0, index = 0;
while ((index = originalString.IndexOf(oldValue, startIndex, comparisonType)) != indexNotFound)
{
originalString = originalString.Substring(0, index) + newValue + originalString.Substring(index + oldValue.Length);
startIndex = index + newValue.Length;
}
return originalString;
}
Replace("FOOBAR", "O", "za", StringComparison.OrdinalIgnoreCase);
// "FzazaBAR"
Replace("", "O", "za", StringComparison.OrdinalIgnoreCase);
// ""
Replace("FOO", "BAR", "", StringComparison.OrdinalIgnoreCase);
// "FOO"
Replace("FOO", "F", "", StringComparison.OrdinalIgnoreCase);
// "OO"
Replace("FOO", "", "BAR", StringComparison.OrdinalIgnoreCase);
// "FOO"
答案 5 :(得分:1)
此功能在带有String.Replace
的.NET Core 2.0 + 中本地可用,具有以下重载
public string Replace (string oldValue, string newValue, StringComparison comparisonType);
public string Replace (string oldValue, string newValue, bool ignoreCase, System.Globalization.CultureInfo culture);
PS :如果您想了解MS的实施方式,可以browse .NET Core source
因此您可以使用以下任一方法:
"A".Replace("a", "b", StringComparison.CurrentCultureIgnoreCase);
"A".Replace("a", "b", true, CultureInfo.CurrentCulture);
Visual Basic具有Option Compare
设置,可以将其设置为Binary
或Text
设置为Text
将默认使整个项目中的所有字符串比较都不区分大小写。
因此,正如其他答案所建议的那样,如果您要插入Microsoft.VisualBasic.dll
,则在调用Strings.Replace
时,如果未显式传递CompareMethod
,则该方法将{{3} },使用[OptionCompare]
参数属性
因此以下任意一项也将起作用( top选项仅在VB中可用,但都依赖于VisualBasic.dll )
Option Compare Text
Replace("A","a","b")
Replace("A","a","b", Compare := CompareMethod.Text)
答案 6 :(得分:0)
您可以使用Microsoft.VisualBasic.Strings.Replace
并传入Microsoft.VisualBasic.CompareMethod.Text
进行不区分大小写的替换,如下所示:
Dim myString As String = "One Two Three"
myString = Replace(myString, "two", "TWO", Compare:= CompareMethod.Text)
答案 7 :(得分:0)
我知道框架中没有固定的实例,但是这里有另一个扩展方法版本,只有少量的语句(尽管可能不是最快),为了好玩。更新版本的替换功能发布在http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx和&#34; Is there an alternative to string.Replace that is case-insensitive?&#34;同样。
public static string ReplaceIgnoreCase(this string alterableString, string oldValue, string newValue){
if(alterableString == null) return null;
for(
int i = alterableString.IndexOf(oldValue, System.StringComparison.CurrentCultureIgnoreCase);
i > -1;
i = alterableString.IndexOf(oldValue, i+newValue.Length, System.StringComparison.CurrentCultureIgnoreCase)
) alterableString =
alterableString.Substring(0, i)
+newValue
+alterableString.Substring(i+oldValue.Length)
;
return alterableString;
}
答案 8 :(得分:0)
可能有点偏离主题,但是自(?)以来,标准替换函数涵盖了不区分大小写的替换,这里的一个小函数可以在子字符串之前和/或之后添加文本,而无需更改子字符串的大小写:
Public Shared Function StrWrap(Haystack As String, Needle As String, Optional AddBefore As String = "", Optional AddAfter As String = "") As String
Dim Index = Haystack.ToLower.IndexOf(Needle.ToLower)
If Index < 0 Then Return Haystack
Return Haystack.Substring(0, Index) + AddBefore + Haystack.Substring(Index, Needle.Length) + AddAfter + Haystack.Substring(Index + Needle.Length)
End Function
用法:StrWrap("Hello World Test", "hello", "Hi, ", " and Ahoi")
结果:“嗨,你好,Ahoi世界测试”
标准不区分大小写的替换:
Replace("Hello World Test", "hello", "Hi", , Compare:=CompareMethod.Text)