C# String Replace高效的实例方法

时间:2021-05-20

复制代码 代码如下:
[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);
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章