将字符串(在数组中)的所有出现替换为单个值

本文关键字:替换 单个值 字符串 数组 | 更新日期: 2023-09-27 18:17:56

我有一个字符串数组:

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("&", "_");

但是我要替换的字符数组可能会变得更大

将字符串(在数组中)的所有出现替换为单个值

不用一遍又一遍地使用Replace,你可以自己写。由于您提到了

,这甚至可能会提高性能。

但是我的数组可能会变得更大

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, char replacement, string replaceables)
{
    return Replace(original, replacement, replaceables.ToCharArray());
}

可以这样调用:

Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', '/', '@', '&'));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', new[] { '/', '@', '&' }));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', existingArray));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_',"/@&"));
输出:

a_ new string, with some_ values_
a_ new string, with some_ values_
a_ new string, with some_ values_
a_ new string, with some_ values_

正如@Sebi指出的,这也可以作为一个扩展方法:

public static class StringExtensions
{
    public static string Replace(this 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 static string Replace(this string original, char replacement, string replaceables)
    {
        return Replace(original, replacement, replaceables.ToCharArray());
    }
}

用法:

"a/ new string, with some@ values&".Replace('_', '/', '@', '&');
existingString.Replace('_', new[] { '/', '@', '&' });
// etc.

这就是我如何从分隔符列表中构建一个regex子句并将它们替换为下划线

string[] delimiters = { "/", "@", "&" };
string clause = $"[{string.Join("]|[", delimiters)}]";
string strValue = "a/ new string, with some@ values&";
Regex chrsToReplace = new Regex(clause);
string output = chrsToReplace.Replace(strValue, "_");

您可能想要封装在if(delimiters.Any())中,否则如果数组为空

它将崩溃

当然。这里有一个方法:

var newString = arr2.Aggregate(strValue, (net, curr) => net.Replace(curr, "_"));

如果您只替换单个字符,并且需要优化的输入大小足够大,则可以创建一个用于替换的集合:

var substitutions = new HashSet<char>() { '/', '@', '&' };
var strValue = "a/ new string, with some@ values&";
var newString = new string(strValue.Select(c => substitutions.Contains(c) ? '_' : c).ToArray());

也许不是最快的,但最简单的是SelectContains

像这样:source.Select(c => blacklist.Contains(c) ? letter : c)

. net Demo .

using System;
using System.Linq;
public class Program
{
    public static void Main()
    {
        var strValue = "a/ new string, with some@ values&";
        Console.WriteLine(strValue.Replace("/@&", '_'));
    }
}
public static class Extensions {
    public static string Replace(this string source, string blacklist, char letter) => 
        new string(source.Select(c => blacklist.Contains(c) ? letter : c).ToArray());
}

你可以用你的list of string拆分你的字符串[]:

string[] arr2 = { "/", "@", "&" };
string strValue = "a/ new string, with some@ values&";
string Output = null;
string[] split = strValue.Split(arr2, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in split)
{
    Output += item + "_";
}
Console.WriteLine(Output);
//-> a_ new string, with some_ values_


更新了@aloisdg评论的答案(有趣的文章,谢谢)。

string[] arr2 = { "/", "@", "&" };
string strValue = "a/ new string, with some@ values&";
string[] split = strValue.Split(arr2, StringSplitOptions.RemoveEmptyEntries);
StringBuilder Output = new StringBuilder();
foreach (var item in split)
{
    Output.Append(item + "_");
}
Console.WriteLine(Output);
//-> a_ new string, with some_ values_

您可以在单行中使用foreach来达到您想要的效果:

arr2.ToList().ForEach(x => strValue = strValue.Replace(x, "_"));