2010-09-03 13 views
0

我要插入的空間中的字符串爲什麼在指定的代碼中指定的限制之後沒有插入空格?

public string MySplit() 
{ 
string SplitThis = "aaaaaaaaaaaa"; // assume that string has more than 34 chars 
string[] array = new string[SplitThis .Length/34]; 
for (int i = 1; i <= array.Length; i++) 
{ 
    SplitThis .Insert(i * 34, " "); 
} 
return SplitThis; 
} 
當我快速監視

每34個字符 「SplitThis .Insert(I * 34」, 「);」我可以看到空格,但結果字符串不顯示空格。爲什麼?

+0

這可能是更快地創建具有預定緩衝區大小一個StringBuilder,然後在循環填充它。 – jgauffin 2010-09-03 11:04:42

回答

7

您扔掉插入的結果 嘗試

SplitThis = SplitThis.Insert(I * 34「,「);

但是在你的代碼中可能會有其他的邏輯錯誤,因爲你正在修改相同的字符串,因爲你正在使用一個字符串,並且已經根據字符串的長度計算了迭代次數,而忽略了長度字符串正在改變。

+0

沒錯。永遠記得字符串是不可變的。 – 2010-09-03 10:46:22

+0

反對!關於字符串的短期記憶喪失導致這個問題:)謝謝 – 2010-09-03 10:49:59

+0

謝謝!這是照顧我的原代碼:) – 2010-09-03 10:53:20

相關問題