2012-08-06 70 views
0

我有一個stringbuilder,我操縱了好幾次,我需要用不同長度的字符串替換它內部的字符串。StringBuilder ReplaceAt功能

sb = new StringBuilder("This has {Count} Values. Your search was '{SearchText}'. Did you mean '{DidYouMean}'?") 
//get the replacement areas, this would search for the field names within {} 
MatchCollection matches = GetReplacementAreas(sb); 

int indexOffset=0; 
foreach(Match m in matches) 
{ 
    //fields is a dictionary containing keys that match the fields 
    sb.ReplaceAt(m.Index,m.Length,fields[m.Value]); 
} 

很明顯ReplaceAt不存在。我即將自己寫。其他人已經這樣做了嗎?

+2

不太確定爲什麼你不會只使用[String.Format](http://msdn.microsoft.com/en-us/library/system.string.format.aspx)或[StringBuilder。 AppendFormat](http://msdn.microsoft.com/zh-cn/library/system.text.stringbuilder.appendformat.aspx)現有功能? – 2012-08-06 15:35:19

+0

我接受它你不能只是使用標準的'替換'方法,一旦你有比賽告訴你你要更換什麼? – Chris 2012-08-06 15:43:05

+0

@MikeGuthrie:我認爲這個想法是,大括號內的內容可以是任何東西,並且它與數據對象匹配並動態執行這些子概念。即在編譯時你不知道字符串中會出現什麼,所以你不能將正確的值作爲參數傳遞給'String.Format'或類似的東西。 – Chris 2012-08-06 15:44:35

回答

0
public static class StringBuilderExtensions 
{ 
#if EXTENSIONS_SUPPORTED 
    public static StringBuilder ReplaceAt(this StringBuilder sb, string value, int index, int count) 
    { 
     return StringBuilderExtensions.ReplaceAt(sb, value, index, count); 
    } 
#endif 

    public static StringBuilder ReplaceAt(StringBuilder sb, string value, int index, int count) 
    { 
     if (value == null) 
     { 
      sb.Remove(index, count); 
     } 
     else 
     { 
      int lengthOfValue = value.Length; 

      if (lengthOfValue > count) 
      { 
       string valueToInsert = value.Substring(count); 
       sb.Insert(index + count, valueToInsert); 
      } 
      if (lengthOfValue < count) 
      { 
       sb.Remove(index + count, lengthOfValue - count); 
      } 

      char[] valueChars = value.ToCharArray(); 
      for (int i = 0; i < lengthOfValue; i++) 
      { 
       sb[index + i] = valueChars[i]; 
      } 
     } 

     return sb; 
    } 
} 
+0

請注意,這不是一個特別高效的操作。 StringBuilder被設計爲高效地添加到最後,而不是有效地修改已經添加的內容。如果使用這種方法,你將失去使用'StringBuilder'的大部分好處。 – Servy 2012-08-06 16:41:09

+0

與每個替換操作在內存中創建一堆字符串相反嗎?通過移位字節可以更有效地騰出空間,特別是當緩衝區結束時正常鬆弛,然後創建全新的字符串時。 – enorl76 2014-12-23 15:03:49

+0

我並沒有說這是做這件事的最好方式,只是這只是稍微好一些。通過在發現替換時移動替換來創建可變結構中的字符串將比您提到的任何一個選項都更具性能。 – Servy 2015-01-02 15:49:36