2016-05-04 49 views
0

運行下面的代碼時,我得到一個運行時異常fix:Index是數組的邊界之外的範圍之外:修復:索引數組的

char[] delim = { ' ' }; 
    string sContent = txtcontent.Text; 
    string sFind = txtfind.Text; 
    string sReplace = txtreplace.Text; 
    string sRecontent = txtrepalcecontent.Text; 
    //Session["find"] = sFind; 
    string[] fileLineString = new string[sContent.Length]; 
    for (int i =0 ; i < sContent.Length; i++) 

    { 
     //fileLineString[0] = sContent[0].ToString(); 
     string[] content = sContent.Split(delim); 
     if (sFind == content[i]) ////**error** 
      //if (Session["find"].ToString() == content[i]) 
     { 
      string A = sContent.Remove(i, txtfind.Text.Length); 
      string S = A.Insert(i, sReplace); 
      txtrepalcecontent.Text = S; 
     } 

回答

0

的問題是在這裏:

string[] content = sContent.Split(delim); 
    if (sFind == content[i]) ////**error** 

您正在遍歷一個長度爲nm的數組,其中m是另一個數組的長度(較短,因爲該數組是拆分的結果,所以您要刪除字符並縮短長度),但仍然期望數組長度爲n。這就是你得到索引越界的方式。 要修復它,只是換週期之前移動拆分並用相同的指標迭代:

char[] delim = { ' ' }; 
string sContent = txtcontent.Text; 
string sFind = txtfind.Text; 
string sReplace = txtreplace.Text; 
string sRecontent = txtrepalcecontent.Text; 
//Session["find"] = sFind; 
string[] content = sContent.Split(delim); 
string[] fileLineString = new string[content.Length]; 
for (int i =0 ; i < content.Length; i++) 
{ 
    //fileLineString[0] = sContent[0].ToString(); 

    if (sFind == content[i]) ////**error** 
     //if (Session["find"].ToString() == content[i]) 
    { 
     string A = sContent.Remove(i, txtfind.Text.Length); 
     string S = A.Insert(i, sReplace); 
     txtrepalcecontent.Text = S; 
    } 
0
string A = sContent.Remove(i, txtfind.Text.Length); 
    string S = A.Insert(i, sReplace); 
    txtrepalcecontent.Text = S; 

如何更換無需替換功能