替换在C#中的多个字符串元素 [英] Replace Multiple String Elements in C#

查看:232
本文介绍了替换在C#中的多个字符串元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有这样做的更好的办法...

Is there a better way of doing this...

MyString.Trim().Replace("&", "and").Replace(",", "").Replace("  ", " ")
         .Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();

我已经扩展了串类,以保持下来的一个工作,但有一个更快的方法?

I've extended the string class to keep it down to one job but is there a quicker way?

public static class StringExtension
{
    public static string clean(this string s)
    {
        return s.Replace("&", "and").Replace(",", "").Replace("  ", " ")
                .Replace(" ", "-").Replace("'", "").Replace(".", "")
                .Replace("eacute;", "é").ToLower();
    }
}


只是为了好玩(并停止在评论的论点)
我猛的向上精神标杆下面的各种例子。


Just for fun (and to stop the arguments in the comments) I've shoved a gist up benchmarking the various examples below.

https://gist.github.com/ChrisMcKee/5937656

正则表达式选项得分可怕;字典选项出现的最快的; StringBuilder中的替换长篇大论版本比手短稍快。

The regex option scores terribly; the dictionary option comes up the fastest; the long winded version of the stringbuilder replace is slightly faster than the short hand.

推荐答案

更​​快 - 没有。更有效的 - 是的,如果你会使用的StringBuilder 类。有了您的实现每个操作产生哪些情况下可能会降低性能的字符串的副本。字符串是的一成不变的对象,因此每次操作只返回一个修改后的副本。

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

如果您希望这种方法能够积极呼吁多个字符串显著的长度,它可能是更好的实施迁移到 StringBuilder的类。有了它,任何修改是在该实例上直接进行的,所以你饶了不必要的复制操作。

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

这篇关于替换在C#中的多个字符串元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆