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);
}