string strToBeReplaced

时间:2022-02-16 08:26:20

前一阵遇到一个如标题的算法题,是将原有字符串的某些片段替换成指定的新字符串片段,例如将源字符串:abcdeabcdfbcdefg中的cde替换成12345,,得到功效字符串:ab12345abcdfb12345fg,即:abcdeabcdfbcdefg -> ab12345abcdfb12345fg。


二、实现要领:

显然不能用string.WordStr要领,需要自界说一个要领 string WordStr(string originalString, string strToBeWordStrd, string strToWordStr),下面是我的实现代码,在半个小时内完成,通过了调试和通例数据的测试验证,还算是及格吧。


代码如下:


public static string WordStr(string originalString, string strToBeWordStrd, string strToWordStr)

{

string resultString = null;

char[] originalCharArray = originalString.ToCharArray();

char[] strToBeCharArray = strToBeWordStrd.ToCharArray();

char[] strToCharArray = strToWordStr.ToCharArray();

List<Char> newCharList = new List<Char>();

for (int i = 0; i < originalCharArray.Count(); i++)

{

if (originalCharArray[i] == strToBeCharArray[0])

{

bool IsWordStr = false;

for (int j = 0; j < strToBeCharArray.Count(); j++)

{

if (((i + j) < originalCharArray.Count())

&& (originalCharArray[i + j] == strToBeCharArray[j]))

{

IsWordStr = true;

}

else

{

IsWordStr = false;

break;

}

}

if (IsWordStr)

{

i += strToBeCharArray.Count() – 1;

for (int k = 0; k < strToCharArray.Count(); k++)

{

newCharList.Add(strToCharArray[k]);

}

}

else

{

newCharList.Add(originalCharArray[i]);

}

}

else

{

newCharList.Add(originalCharArray[i]);

}

}

resultString = string.Join(“”, newCharList);

return resultString;

}