加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:11:11 所属栏目:百科 来源:网络整理
导读:我有一个字符串数组: string[] arr2 = { "/","@","" }; 我有另一个字符串(即strValue).是否有一种干净的方法用单个值(即下划线)替换数组内容的所有实例?所以之前: strValue = "a/ new string,with some@ values" 之后: strValue = "a_ new string,with s
我有一个字符串数组:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读