I recently had to perform some string replacements in .net and found myself developing a regular expression replacement function for this purpose. After getting it to work I couldn't help but think there must be a built in case insensitive replacement operation in .Net that I'm missing?
我最近不得不在.net中执行一些字符串替换,并发现自己为此目的开发了一个正则表达式替换函数。在开始工作之后,我忍不住想到.Net中必须有一个内置的不区分大小写的替换操作,我不知道了吗?
Surely when there are so many other string operations that support case insensitive comparission such as;
当有许多其他字符串操作支持不区分大小写的比较时,例如;
var compareStrings = String.Compare("a", "b", blIgnoreCase);
var equalStrings = String.Equals("a", "b", StringComparison.CurrentCultureIgnoreCase);
then there must be a built in equivalent for replace?
那么必须有一个内置的等效替换?
8 个解决方案
#1
20
Found one in the comments here: http://www.codeproject.com/Messages/1835929/this-one-is-even-faster-and-more-flexible-modified.aspx
在这里的评论中找到一个: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();
}
Should be the fastest, but i haven't checked.
应该是最快的,但我还没有检查过。
Otherwise you should do what Simon suggested and use the VisualBasic Replace function. This is what i always do because of its case-insensitive capabilities (i'm usually a VB.Net programmer).
否则你应该做Simon建议的并使用VisualBasic Replace函数。这是我一直以来所做的,因为它不区分大小写(我通常是VB.Net程序员)。
string s = "SoftWare";
s = Microsoft.VisualBasic.Strings.Replace(s, "software", "hardware", 1, -1, Constants.vbTextCompare);
You have to add a reference to the Microsoft.VisualBasic dll.
您必须添加对Microsoft.VisualBasic dll的引用。
#2
12
It's not ideal, but you can import Microsoft.VisualBasic
and use Strings.Replace
to do this. Otherwise I think it's case of rolling your own or stick with Regular Expressions.
它并不理想,但您可以导入Microsoft.VisualBasic并使用Strings.Replace来执行此操作。否则我认为这是自己滚动或坚持使用正则表达式的情况。
#3
3
Here's an extension method. Not sure where I found it.
这是一种扩展方法。不知道我在哪里找到它。
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;
}
}
#4
1
My 2 cents:
我的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
This is a VB.NET adaptation of rboarman's method with necessary checks for null and empty strings to avoid an infinite loop.
这是对rboarman方法的VB.NET改编,必须检查null和空字符串以避免无限循环。
Public Function Replace(ByVal originalString As String, ByVal oldValue As String, newValue As String, ByVal comparisonType As StringComparison) As String
If String.IsNullOrEmpty(originalString) = False AndAlso String.IsNullOrEmpty(oldValue) = False AndAlso IsNothing(newValue) = False 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
#6
0
Well, the built-in String.Replace
just does not support case-insensitive search. It's documented:
好吧,内置的String.Replace只是不支持不区分大小写的搜索。它记录在案:
This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue.
此方法执行序数(区分大小写和区分大小写)搜索以查找oldValue。
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
It should not be, however, too difficult to create your own extension.
但是,创建自己的扩展程序不应该太难。
#7
0
I know of no canned instance in the framework, but here's another extension method version with a minimal amount of statements (although maybe not the fastest), for fun. More versions of replacement functions are posted at http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx and "Is there an alternative to string.Replace that is case-insensitive?" as well.
我知道框架中没有固定的实例,但是这里是另一个扩展方法版本,只需要很少的语句(尽管可能不是最快的),这很有趣。更多版本的替换函数发布在http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx和“是否有一个不区分大小写的string.Replace替代?”同样。
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
-1
Returns a string in which a specified substring has been replaced with another substring a specified number of times
It has one optional Microsoft.VisualBasic.CompareMethod paramater to specify the kind of comparison to use when evaluating substrings
返回一个字符串,其中指定的子字符串已被指定的次数替换为另一个子字符串它有一个可选的Microsoft.VisualBasic.CompareMethod参数,用于指定在评估子字符串时要使用的比较类型
Dim mystring As String = "One Two Three"
mystring = Replace(mystring, "two", "TWO", 1, , CompareMethod.Text)
#1
20
Found one in the comments here: http://www.codeproject.com/Messages/1835929/this-one-is-even-faster-and-more-flexible-modified.aspx
在这里的评论中找到一个: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();
}
Should be the fastest, but i haven't checked.
应该是最快的,但我还没有检查过。
Otherwise you should do what Simon suggested and use the VisualBasic Replace function. This is what i always do because of its case-insensitive capabilities (i'm usually a VB.Net programmer).
否则你应该做Simon建议的并使用VisualBasic Replace函数。这是我一直以来所做的,因为它不区分大小写(我通常是VB.Net程序员)。
string s = "SoftWare";
s = Microsoft.VisualBasic.Strings.Replace(s, "software", "hardware", 1, -1, Constants.vbTextCompare);
You have to add a reference to the Microsoft.VisualBasic dll.
您必须添加对Microsoft.VisualBasic dll的引用。
#2
12
It's not ideal, but you can import Microsoft.VisualBasic
and use Strings.Replace
to do this. Otherwise I think it's case of rolling your own or stick with Regular Expressions.
它并不理想,但您可以导入Microsoft.VisualBasic并使用Strings.Replace来执行此操作。否则我认为这是自己滚动或坚持使用正则表达式的情况。
#3
3
Here's an extension method. Not sure where I found it.
这是一种扩展方法。不知道我在哪里找到它。
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;
}
}
#4
1
My 2 cents:
我的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
This is a VB.NET adaptation of rboarman's method with necessary checks for null and empty strings to avoid an infinite loop.
这是对rboarman方法的VB.NET改编,必须检查null和空字符串以避免无限循环。
Public Function Replace(ByVal originalString As String, ByVal oldValue As String, newValue As String, ByVal comparisonType As StringComparison) As String
If String.IsNullOrEmpty(originalString) = False AndAlso String.IsNullOrEmpty(oldValue) = False AndAlso IsNothing(newValue) = False 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
#6
0
Well, the built-in String.Replace
just does not support case-insensitive search. It's documented:
好吧,内置的String.Replace只是不支持不区分大小写的搜索。它记录在案:
This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue.
此方法执行序数(区分大小写和区分大小写)搜索以查找oldValue。
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
It should not be, however, too difficult to create your own extension.
但是,创建自己的扩展程序不应该太难。
#7
0
I know of no canned instance in the framework, but here's another extension method version with a minimal amount of statements (although maybe not the fastest), for fun. More versions of replacement functions are posted at http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx and "Is there an alternative to string.Replace that is case-insensitive?" as well.
我知道框架中没有固定的实例,但是这里是另一个扩展方法版本,只需要很少的语句(尽管可能不是最快的),这很有趣。更多版本的替换函数发布在http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx和“是否有一个不区分大小写的string.Replace替代?”同样。
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
-1
Returns a string in which a specified substring has been replaced with another substring a specified number of times
It has one optional Microsoft.VisualBasic.CompareMethod paramater to specify the kind of comparison to use when evaluating substrings
返回一个字符串,其中指定的子字符串已被指定的次数替换为另一个子字符串它有一个可选的Microsoft.VisualBasic.CompareMethod参数,用于指定在评估子字符串时要使用的比较类型
Dim mystring As String = "One Two Three"
mystring = Replace(mystring, "two", "TWO", 1, , CompareMethod.Text)