用C#写的一个替换函数
今天因程序的需要写了一个替换函数
但始终感觉不太好.
听说正则表达式可以实现这种功能,而且非常简单.
但由于对正则完全不熟,还请高人指教.
//替换函数
public string replace(string str1,string str2,string str3)
{
char[] sourceValues = str1.ToCharArray();
char[] oldValues = str2.ToCharArray();
char[] newValues = str3.ToCharArray();
int beginSign = 0;
int endSign = 0;
string returnValues = "";
string strNew = "";
for (int i = 0; i < newValues.Length; i++)
{
strNew += newValues[i];
}
for (int i = 0; i < sourceValues.Length; i++)
{
for (int j = 0; j < oldValues.Length && i<sourceValues.Length; j++,i++)
{
if (sourceValues[i] == oldValues[j])
{
}
else
{
break;
}
if (j == oldValues.Length - 1)
{
beginSign = i - j;
endSign = i;
string temp1 = "";
string temp2 = "";
for (int k = 0; k < beginSign; k++)
{
temp1 += sourceValues[k];
}
for (int k = endSign + 1; k < sourceValues.Length; k++)
{
temp2 += sourceValues[k];
}
string newSourceValues = temp1 + strNew + temp2;
sourceValues = newSourceValues.ToCharArray();
i--;
}
}
}
for (int i = 0; i < sourceValues.Length; i++)
{
returnValues += sourceValues[i];
}
return returnValues;
}
public string replace(string str1,string str2,string str3)
{
char[] sourceValues = str1.ToCharArray();
char[] oldValues = str2.ToCharArray();
char[] newValues = str3.ToCharArray();
int beginSign = 0;
int endSign = 0;
string returnValues = "";
string strNew = "";
for (int i = 0; i < newValues.Length; i++)
{
strNew += newValues[i];
}
for (int i = 0; i < sourceValues.Length; i++)
{
for (int j = 0; j < oldValues.Length && i<sourceValues.Length; j++,i++)
{
if (sourceValues[i] == oldValues[j])
{
}
else
{
break;
}
if (j == oldValues.Length - 1)
{
beginSign = i - j;
endSign = i;
string temp1 = "";
string temp2 = "";
for (int k = 0; k < beginSign; k++)
{
temp1 += sourceValues[k];
}
for (int k = endSign + 1; k < sourceValues.Length; k++)
{
temp2 += sourceValues[k];
}
string newSourceValues = temp1 + strNew + temp2;
sourceValues = newSourceValues.ToCharArray();
i--;
}
}
}
for (int i = 0; i < sourceValues.Length; i++)
{
returnValues += sourceValues[i];
}
return returnValues;
}