欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# String Replace高效的实例方法

程序员文章站 2023-12-18 23:12:46
复制代码 代码如下:[threadstatic]        static char[] mtemp...
复制代码 代码如下:

[threadstatic]
        static char[] mtempchars;

        protected static char[] gettempdata()
        {
            if (mtempchars == null)
                mtempchars = new char[1024 * 64];
            return mtempchars;
        }

        public static string replace(string value, string olddata, string newdata)
        {
            char[] tmpchars = gettempdata();
            int newpostion = 0;
            int oldpostion = 0;
            int length = value.length;
            int oldlength = olddata.length;
            int newlength = newdata.length;
            int index = 0;
            int copylength = 0;
            bool eq = false;
            while (index < value.length)
            {
                eq = true;
                for (int k = 0; k < oldlength; k++)
                {
                    if (value[index + k] != olddata[k])
                    {
                        eq = false;
                        break;
                    }

                }
                if (eq)
                {
                    copylength = index - oldpostion;
                    value.copyto(oldpostion, tmpchars, newpostion, copylength);
                    newpostion += copylength;
                    index += oldlength;
                    oldpostion = index;
                    newdata.copyto(0, tmpchars, newpostion, newlength);
                    newpostion += newlength;

                }
                else
                {
                    index++;
                }
            }
            if (oldpostion < length)
            {
                copylength = index - oldpostion;
                value.copyto(oldpostion, tmpchars, newpostion, copylength);
                newpostion += copylength;
            }
            return new string(tmpchars, 0, newpostion);
        }

上一篇:

下一篇: