C#自訂字串替換Replace方法執行個體

來源:互聯網
上載者:User

標籤:normal   size   strong   nbsp   bottom   執行個體   title   count()   ima   

本文執行個體講述了C#自訂字串替換Replace方法。分享給大家供大家參考。具體實現方法如下:


一、問題:

前一陣遇到一個如標題的演算法題,是將原有字串的某些片段替換成指定的新字串片段,例如將源字串:abcdeabcdfbcdefg中的cde替換成12345,得到結果字串:ab12345abcdfb12345fg,即:abcdeabcdfbcdefg -> ab12345abcdfb12345fg。


二、實現方法:

顯然不能用string.Replace方法,需要自訂一個方法 string Replace(string originalString, string strToBeReplaced, string strToReplace),下面是我的實現代碼,在半個小時內完成,通過了調試和常規資料的測實驗證,還算是及格吧。


代碼如下:


public static string Replace(string originalString, string strToBeReplaced, string strToReplace)

{

string resultString = null;

char[] originalCharArray = originalString.ToCharArray();

char[] strToBeCharArray = strToBeReplaced.ToCharArray();

char[] strToCharArray = strToReplace.ToCharArray();

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

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

{

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

{

bool IsReplace = false;

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

{

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

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

{

IsReplace = true;

}

else

{

IsReplace = false;

break;

}

}

if (IsReplace)

{

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;

}

除聲明外, 跑步客文章均為原創,轉載請以連結形式標明本文地址
  C#自訂字串替換Replace方法執行個體

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23319.html






相關內容C#使用Regex隱藏手機號中間四位為*C# 計算標準差相當於Excel中的STDEV函數執行個體C#實現的網頁授權操作邏輯封裝樣本C#中判斷一個集合是否是另一個集合的子集的簡單方法
C#編程實現取整和取餘的方法C#驗證給定字串形式日期是否合法的方法C#實現發送郵件的三種方法C#實現對Json字串處理執行個體

C#自訂字串替換Replace方法執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.