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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/92479.html

猜你在找的C#相关文章