替换c#字符串中的多个字符

时间:2022-07-05 16:53:03

Is there a better way to replace strings?

有更好的替代字符串的方法吗?

I am surprised that Replace does not take in a character array or string array. I guess that I could write my own extension but I was curious if there is a better built in way to do the following? Notice the last Replace is a string not a character.

我很惊讶Replace不接受字符数组或字符串数组。我想我可以写我自己的扩展,但是我很好奇是否有更好的方法来做下面的事情?注意,最后的替换是字符串而不是字符。

myString.Replace(';', '\n').Replace(',', '\n').Replace('\r', '\n').Replace('\t', '\n').Replace(' ', '\n').Replace("\n\n", "\n");

9 个解决方案

#1


152  

You can use a replace regular expression.

可以使用替换正则表达式。

s/[;,\t\r ]|[\n]{2}/\n/g
  • s/ at the beginning means a search
  • s/在开始意味着搜索
  • The characters between [ and ] are the characters to search for (in any order)
  • [和]之间的字符是要搜索的字符(以任何顺序)
  • The second / delimits the search-for text and the replace text
  • 第二项是搜索文本和替换文本

In English, this reads:

在英语中,这写着:

"Search for ; or , or \t or \r or (space) or exactly two sequential \n and replace it with \n"

“搜索;或者,或\t或\r或(空间)或恰好两个顺序\n,并将其替换为\n

In C#, you could do the following: (after importing System.Text.RegularExpressions)

在c#中,您可以执行以下操作:(在导入System.Text.RegularExpressions之后)

Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");

#2


88  

If you are feeling particularly clever and don't want to use Regex:

如果你觉得自己特别聪明,不想使用Regex:

char[] separators = new char[]{' ',';',',','\r','\t','\n'};

string s = "this;is,\ra\t\n\n\ntest";
string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
s = String.Join("\n", temp);

You could wrap this in an extension method with little effort as well.

你也可以用扩展的方法把它包装起来,也不费什么力气。

Edit: Or just wait 2 minutes and I'll end up writing it anyway :)

编辑:或者等2分钟,我就写下来了:)

public static class ExtensionMethods
{
   public static string Replace(this string s, char[] separators, string newVal)
   {
       string[] temp;

       temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
       return String.Join( newVal, temp );
   }
}

And voila...

瞧……

char[] separators = new char[]{' ',';',',','\r','\t','\n'};
string s = "this;is,\ra\t\n\n\ntest";

s = s.Replace(separators, "\n");

#3


42  

You could use Linq's Aggregate function:

您可以使用Linq的聚合函数:

string s = "the\nquick\tbrown\rdog,jumped;over the lazy fox.";
char[] chars = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
string snew = chars.Aggregate(s, (c1, c2) => c1.Replace(c2, '\n'));

Here's the extension method:

扩展方法是这样的:

public static string ReplaceAll(this string seed, char[] chars, char replacementCharacter)
{
    return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, replacementCharacter));
}

#4


14  

This is the shortest way:

这是最短的方法:

myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");

#5


5  

Ohhh, the performance horror! The answer is a bit outdated, but still...

呵呵,性能恐怖了。答案有点过时了,但是……

public static class StringUtils
{
    #region Private members

    [ThreadStatic]
    private static StringBuilder m_ReplaceSB;

    private static StringBuilder GetReplaceSB(int capacity)
    {
        var result = m_ReplaceSB;

        if (null == result)
        {
            result = new StringBuilder(capacity);
            m_ReplaceSB = result;
        }
        else
        {
            result.Clear();
            result.EnsureCapacity(capacity);
        }

        return result;
    }


    public static string ReplaceAny(this string s, char replaceWith, params char[] chars)
    {
        if (null == chars)
            return s;

        if (null == s)
            return null;

        StringBuilder sb = null;

        for (int i = 0, count = s.Length; i < count; i++)
        {
            var temp = s[i];
            var replace = false;

            for (int j = 0, cc = chars.Length; j < cc; j++)
                if (temp == chars[j])
                {
                    if (null == sb)
                    {
                        sb = GetReplaceSB(count);
                        if (i > 0)
                            sb.Append(s, 0, i);
                    }

                    replace = true;
                    break;
                }

            if (replace)
                sb.Append(replaceWith);
            else
                if (null != sb)
                    sb.Append(temp);
        }

        return null == sb ? s : sb.ToString();
    }
}

#6


2  

Strings are just immutable char arrays

You just need to make it mutable:

你只需要使它可变:

  • either by using StringBuilder
  • 通过使用StringBuilder
  • go in the unsafe world and play with pointers (dangerous though)
  • 进入不安全的世界,玩指针(尽管危险)

and try to iterate through the array of characters the least amount of times.

并尝试遍历字符数组的次数最少。

Example with StringBuilder

StringBuilder的示例

    public static void MultiReplace(this StringBuilder builder, char[] toReplace, char replacement)
    {
        HashSet<char> set = new HashSet<char>(toReplace);
        for (int i = 0; i < builder.Length; ++i)
        {
            var currentCharacter = builder[i];
            if (set.Contains(currentCharacter))
            {
                builder[i] = replacement;
            }
        }
    }

Then you just have to use it like that:

那么你只需要像这样使用它:

var builder = new StringBuilder("my bad,url&slugs");
builder.MultiReplace(new []{' ', '&', ','}, '-');
var result = builder.ToString();

#7


1  

Use RegEx.Replace, something like this:

使用正则表达式。替换,是这样的:

  string input = "This is   text with   far  too   much   " + 
                 "whitespace.";
  string pattern = "[;,]";
  string replacement = "\n";
  Regex rgx = new Regex(pattern);

Here's more info on this MSDN documentation for RegEx.Replace

这里有更多关于RegEx.Replace MSDN文档的信息

#8


1  

Performance-Wise this probably might not be the best solution but it works.

从性能上看,这可能不是最好的解决方案,但它确实有效。

var str = "filename:with&bad$separators.txt";
char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' };
foreach (var singleChar in charArray)
{
   str = str.Replace(singleChar, '_');
}

#9


1  

You may also simply write these string extension methods, and put them somewhere in your solution:

您也可以简单地编写这些字符串扩展方法,并将它们放在您的解决方案中的某个位置:

using System.Text;

public static class StringExtensions
{
    public static string ReplaceAll(this string original, string toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || string.IsNullOrEmpty(toBeReplaced)) return original;
        if (newValue == null) newValue = string.Empty;
        StringBuilder sb = new StringBuilder();
        foreach (char ch in original)
        {
            if (toBeReplaced.IndexOf(ch) < 0) sb.Append(ch);
            else sb.Append(newValue);
        }
        return sb.ToString();
    }

    public static string ReplaceAll(this string original, string[] toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || toBeReplaced == null || toBeReplaced.Length <= 0) return original;
        if (newValue == null) newValue = string.Empty;
        foreach (string str in toBeReplaced)
            if (!string.IsNullOrEmpty(str))
                original = original.Replace(str, newValue);
        return original;
    }
}


Call them like this:

叫他们是这样的:

"ABCDE".ReplaceAll("ACE", "xy");

xyBxyDxy

xyBxyDxy


And this:

这:

"ABCDEF".ReplaceAll(new string[] { "AB", "DE", "EF" }, "xy");

xyCxyF

xyCxyF

#1


152  

You can use a replace regular expression.

可以使用替换正则表达式。

s/[;,\t\r ]|[\n]{2}/\n/g
  • s/ at the beginning means a search
  • s/在开始意味着搜索
  • The characters between [ and ] are the characters to search for (in any order)
  • [和]之间的字符是要搜索的字符(以任何顺序)
  • The second / delimits the search-for text and the replace text
  • 第二项是搜索文本和替换文本

In English, this reads:

在英语中,这写着:

"Search for ; or , or \t or \r or (space) or exactly two sequential \n and replace it with \n"

“搜索;或者,或\t或\r或(空间)或恰好两个顺序\n,并将其替换为\n

In C#, you could do the following: (after importing System.Text.RegularExpressions)

在c#中,您可以执行以下操作:(在导入System.Text.RegularExpressions之后)

Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");

#2


88  

If you are feeling particularly clever and don't want to use Regex:

如果你觉得自己特别聪明,不想使用Regex:

char[] separators = new char[]{' ',';',',','\r','\t','\n'};

string s = "this;is,\ra\t\n\n\ntest";
string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
s = String.Join("\n", temp);

You could wrap this in an extension method with little effort as well.

你也可以用扩展的方法把它包装起来,也不费什么力气。

Edit: Or just wait 2 minutes and I'll end up writing it anyway :)

编辑:或者等2分钟,我就写下来了:)

public static class ExtensionMethods
{
   public static string Replace(this string s, char[] separators, string newVal)
   {
       string[] temp;

       temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
       return String.Join( newVal, temp );
   }
}

And voila...

瞧……

char[] separators = new char[]{' ',';',',','\r','\t','\n'};
string s = "this;is,\ra\t\n\n\ntest";

s = s.Replace(separators, "\n");

#3


42  

You could use Linq's Aggregate function:

您可以使用Linq的聚合函数:

string s = "the\nquick\tbrown\rdog,jumped;over the lazy fox.";
char[] chars = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
string snew = chars.Aggregate(s, (c1, c2) => c1.Replace(c2, '\n'));

Here's the extension method:

扩展方法是这样的:

public static string ReplaceAll(this string seed, char[] chars, char replacementCharacter)
{
    return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, replacementCharacter));
}

#4


14  

This is the shortest way:

这是最短的方法:

myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");

#5


5  

Ohhh, the performance horror! The answer is a bit outdated, but still...

呵呵,性能恐怖了。答案有点过时了,但是……

public static class StringUtils
{
    #region Private members

    [ThreadStatic]
    private static StringBuilder m_ReplaceSB;

    private static StringBuilder GetReplaceSB(int capacity)
    {
        var result = m_ReplaceSB;

        if (null == result)
        {
            result = new StringBuilder(capacity);
            m_ReplaceSB = result;
        }
        else
        {
            result.Clear();
            result.EnsureCapacity(capacity);
        }

        return result;
    }


    public static string ReplaceAny(this string s, char replaceWith, params char[] chars)
    {
        if (null == chars)
            return s;

        if (null == s)
            return null;

        StringBuilder sb = null;

        for (int i = 0, count = s.Length; i < count; i++)
        {
            var temp = s[i];
            var replace = false;

            for (int j = 0, cc = chars.Length; j < cc; j++)
                if (temp == chars[j])
                {
                    if (null == sb)
                    {
                        sb = GetReplaceSB(count);
                        if (i > 0)
                            sb.Append(s, 0, i);
                    }

                    replace = true;
                    break;
                }

            if (replace)
                sb.Append(replaceWith);
            else
                if (null != sb)
                    sb.Append(temp);
        }

        return null == sb ? s : sb.ToString();
    }
}

#6


2  

Strings are just immutable char arrays

You just need to make it mutable:

你只需要使它可变:

  • either by using StringBuilder
  • 通过使用StringBuilder
  • go in the unsafe world and play with pointers (dangerous though)
  • 进入不安全的世界,玩指针(尽管危险)

and try to iterate through the array of characters the least amount of times.

并尝试遍历字符数组的次数最少。

Example with StringBuilder

StringBuilder的示例

    public static void MultiReplace(this StringBuilder builder, char[] toReplace, char replacement)
    {
        HashSet<char> set = new HashSet<char>(toReplace);
        for (int i = 0; i < builder.Length; ++i)
        {
            var currentCharacter = builder[i];
            if (set.Contains(currentCharacter))
            {
                builder[i] = replacement;
            }
        }
    }

Then you just have to use it like that:

那么你只需要像这样使用它:

var builder = new StringBuilder("my bad,url&slugs");
builder.MultiReplace(new []{' ', '&', ','}, '-');
var result = builder.ToString();

#7


1  

Use RegEx.Replace, something like this:

使用正则表达式。替换,是这样的:

  string input = "This is   text with   far  too   much   " + 
                 "whitespace.";
  string pattern = "[;,]";
  string replacement = "\n";
  Regex rgx = new Regex(pattern);

Here's more info on this MSDN documentation for RegEx.Replace

这里有更多关于RegEx.Replace MSDN文档的信息

#8


1  

Performance-Wise this probably might not be the best solution but it works.

从性能上看,这可能不是最好的解决方案,但它确实有效。

var str = "filename:with&bad$separators.txt";
char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' };
foreach (var singleChar in charArray)
{
   str = str.Replace(singleChar, '_');
}

#9


1  

You may also simply write these string extension methods, and put them somewhere in your solution:

您也可以简单地编写这些字符串扩展方法,并将它们放在您的解决方案中的某个位置:

using System.Text;

public static class StringExtensions
{
    public static string ReplaceAll(this string original, string toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || string.IsNullOrEmpty(toBeReplaced)) return original;
        if (newValue == null) newValue = string.Empty;
        StringBuilder sb = new StringBuilder();
        foreach (char ch in original)
        {
            if (toBeReplaced.IndexOf(ch) < 0) sb.Append(ch);
            else sb.Append(newValue);
        }
        return sb.ToString();
    }

    public static string ReplaceAll(this string original, string[] toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || toBeReplaced == null || toBeReplaced.Length <= 0) return original;
        if (newValue == null) newValue = string.Empty;
        foreach (string str in toBeReplaced)
            if (!string.IsNullOrEmpty(str))
                original = original.Replace(str, newValue);
        return original;
    }
}


Call them like this:

叫他们是这样的:

"ABCDE".ReplaceAll("ACE", "xy");

xyBxyDxy

xyBxyDxy


And this:

这:

"ABCDEF".ReplaceAll(new string[] { "AB", "DE", "EF" }, "xy");

xyCxyF

xyCxyF