且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换在C#中的多个字符串元素

更新时间:2023-02-12 19:11:30

更​​快 - 没有。更有效的 - 是的,如果你会使用的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();
    }
}