我有一个字符串数组:
string[] arr2 = { "/","@","&" };
我有另一个字符串(即strValue).是否有一种干净的方法用单个值(即下划线)替换数组内容的所有实例?所以之前:
strValue = "a/ new string,with some@ values&"
之后:
strValue = "a_ new string,with some_ values_"
我考虑过这样做:
strValue = strValue.Replace("/","_"); strValue = strValue.Replace("@","_"); strValue = strValue.Replace("&","_");
但我要替换的角色数组可能会变得更大.
解决方法
你可以自己编写,而不是一遍又一遍地使用替换.这可能是你提到的性能提升
But my array may get a lot bigger.
public string Replace(string original,char replacement,params char[] replaceables) { StringBuilder builder = new StringBuilder(original.Length); HashSet<char> replaceable = new HashSet<char>(replaceables); foreach(Char character in original) { if (replaceable.Contains(character)) builder.Append(replacement); else builder.Append(character); } return builder.ToString(); } public string Replace(string original,string replaceables) { return Replace(original,replacement,replaceables.tocharArray()); }
可以像这样调用:
Debug.WriteLine(Replace("a/ new string,with some@ values&",'_','/','@','&')); Debug.WriteLine(Replace("a/ new string,new[] { '/','&' })); Debug.WriteLine(Replace("a/ new string,existingArray)); Debug.WriteLine(Replace("a/ new string,"/@&"));
输出:
a_ new string,with some_ values_ a_ new string,with some_ values_
正如@Sebi指出的那样,这也可以作为一种扩展方法:
public static class StringExtensions { public static string Replace(this string original,params char[] replaceables) { StringBuilder builder = new StringBuilder(original.Length); HashSet<Char> replaceable = new HashSet<char>(replaceables); foreach (Char character in original) { if (replaceable.Contains(character)) builder.Append(replacement); else builder.Append(character); } return builder.ToString(); } public static string Replace(this string original,string replaceables) { return Replace(original,replaceables.tocharArray()); } }
用法:
"a/ new string,with some@ values&".Replace('_','&'); existingString.Replace('_','&' }); // etc.