微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个字符串数组:
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.

原文地址:https://www.jb51.cc/csharp/92479.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐