c# – 用单个值替换所有出现的字符串(在数组中)

c# – 用单个值替换所有出现的字符串(在数组中),第1张

概述我有一个字符串数组: string[] arr2 = { "/", "@", "&" }; 我有另一个字符串(即strValue).是否有一种干净的方法用单个值(即下划线)替换数组内容的所有实例?所以之前: strValue = "a/ new string, with some@ values&" 之后: strValue = "a_ new string, with some_ values_ @H_419_0@我有一个字符串数组:
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.
总结

以上是内存溢出为你收集整理的c# – 用单个值替换所有出现的字符串(在数组中)全部内容,希望文章能够帮你解决c# – 用单个值替换所有出现的字符串(在数组中)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1262270.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存