2011-03-23 91 views
1

我試圖在C#字符串的位置插入字符串,其失敗c中的字符串插入問題#

這裏是片段。

if(strCellContent.Contains("<")) 
    { 
     int pos = strCellContent.IndexOf("<"); 
     strCellContent.Insert(pos,"&lt;"); 
    } 

請告訴我解決

+2

你會作爲一種解釋它是如何失敗的? – 2011-03-23 07:06:42

+0

首先,你應該清楚你想插入新的字符串替換「<」或連接新的字符串而不替換< – AsifQadri 2011-03-23 07:19:50

回答

7

返回值包含了你想要的新的字符串。

strCellContent = strCellContent.Insert(pos,"&lt;"); 
1

當我看着你的代碼,我覺得你想要做一個替換,但試試這個:

if(strCellContent.Contains("<"))  
{ 
     int pos = strCellContent.IndexOf("<"); 
     strCellContent = strCellContent.Insert(pos,"&lt;"); 
} 
0

.Contains是不是在這裏是個好主意,因爲你需要知道的位置。該解決方案將更有效率。

int pos = strCellContent.IndexOf("<"); 
if (pos >= 0) //that means the string Contains("<") 
{ 
    strCellContent = strCellContent.Insert(pos,"&lt;"); //string is immutable 
} 
7

炮手和狂想曲給予正確的變化,但它是值得了解的爲什麼原來的嘗試失敗。字符串類型是不可變的 - 一旦你有一個字符串,你不能改變它的內容。所有的方法看起來就像他們正在改變它實際上只是返回一個新值。因此,例如,如果您有:

string x = "foo"; 
string y = x.Replace("o", "e"); 

字符串x指仍包含字符「富」 ......但是字符串y是指將包含字符「費」。

這會影響字符串的所有用法,而不僅僅是您現在正在查看的特定情況(這會更好地使用Replace進行處理,或者更好的還是一個圖書館調用,它知道如何完成所有需要的轉義) 。

+0

是的,這是很容易,然後更早..謝謝lot – Naruto 2011-03-23 12:36:29

2

我想你可能是更好的Replace而不是Insert

strCellContent = strCellContent.Replace("<", "&lt;"); 

也許做Server.HtmlEncode()甚至更​​好:

strCellContent = Server.HtmlEncode(strCellContent); 
+0

+1。面對諸如'HtmlEncode'之類的手段,手動搜索/替換是一個可怕的想法(假設他有能力調用它)。 Xml庫也具有類似的自動轉義功能。 – 2011-03-23 07:13:16