2012-02-02 65 views
2

我們有一個數據表「ST」有兩列「字」,「二進制」獲得「索引數組的範圍之外」異常

void replace() 
    { 

     string s1="", s2="";    
     StreamReader streamReader; 
     streamReader = File.OpenText("C:\\text.txt"); 
     StreamWriter streamWriter = File.CreateText("C:\\sample1.txt"); 
     int x = st.Rows.Count; 
     // int i1 = 0;          
      // Now, read the entire file into a string 
      while ((line = streamReader.ReadLine()) != null) 
      { 
       for (int i = 0; i < x; i++) 
       { 

       s1 = Convert.ToString(st.Rows[i]["Word"]); 
       s2 = Convert.ToString(st.Rows[i]["Binary"]); 
       s2+="000"; 
       char[] delimiterChars = { ' ', '\t' }; 
       String[] words = line.Split(delimiterChars); 

        // Write the modification into the same file      
       String ab = words[i]; //exception occurs here 
       // Console.WriteLine(ab); 
       streamWriter.Write(ab.Replace(s1,s2));         
       }     
      } 
     streamReader.Close(); 
     streamWriter.Close(); 
    } 

我們得到的一個「索引範圍之外的數組「異常。我們無法找到問題。在此先感謝

編輯: tnx給每個人誰幫助。 我這樣做,它以某種方式工作:再次

void replace() 
    { 
     string s1 = "", s2 = ""; 
     StreamReader streamReader; 
     streamReader = File.OpenText("C:\\sample1.txt"); 
     StreamWriter streamWriter = File.CreateText("C:\\sample1.txt"); 
     int x = st.Rows.Count;   
     while ((line = streamReader.ReadLine()) != null) 
     { 
      char[] delimiterChars = { ' ', '\t' }; 
      String[] words = line.Split(delimiterChars); 
      foreach (string str in words) 
      { 

       s1 = str; 
       DataRow drow = st.Rows.Find(str); 
       if (drow != null) 
       { 
        index = st.Rows.IndexOf(drow); 
        s2 = Convert.ToString(st.Rows[index]["Binary"]); 
        // s2 += "000"; 
        // ab = words[i];       
        Console.WriteLine(s1); 
        Console.WriteLine(s2); 
        streamWriter.Write(str.Replace(s1, s2));         
       } 
       else 
        break; 
      }    
     } 
     streamReader.Close(); 
     streamWriter.Close(); 
    } 

TNX給大家。 問候, sagar

回答

0

如果你有一個假想的行「abcde」,例如你的文件的第一行,而你的數據庫「st」包含10行,你可以循環這個過程10次,第6次你會遇到錯誤。第6步將字符串拆分爲:{a,b,c,d,e},然後嘗試獲取第五個索引(基於零),該索引位於數組之外。

+0

那麼我該如何避免它? PLZ幫助 – 2012-02-02 17:24:21

+0

@vidya如果我理解您的示例中的應用程序,您正在查找要替換爲字符串的單詞,然後將修改的字符串放回到文件中。首先,我會提升內部循環之外的所有步驟,分割字符串,而分隔符可以在for循環之外完成。然後在for循環中,您實際上需要查看拆分字符串中的每個單詞以進行替換。這樣做的一種方法是添加一個迭代每個拆分詞的for循環。一個更容易和更直接的方法是使用列表和擴展方法 – GrayWizardx 2012-02-02 17:56:09

+0

我會嘗試列表。謝謝你的幫助 – 2012-02-02 18:11:06

5

你基於我的方式是行數又名X而不是字符串數組的長度。因此,您可能有100行,但字符串僅分成5個字符串值。

2

i是您所在行的索引。

while ((line = streamReader.ReadLine()) != null) 
{ 
    for (int i = 0; i < x; i++) // say we are on line 20 

words包含該行上單詞的數組。

String[] words = line.Split(delimiterChars); // say there are 3 words on line 20 

如果行中的單詞少於行索引...則會出現越界異常。

String ab = words[i]; // trying to get to word 20 out of 3... 

你需要使用一個有效的索引值在該行的單詞數 - 目前尚不清楚你想在你的代碼來實現什麼,所以我不能提供一個例子。

0

使用調試器,以查看linewords陣列中的內容,並將其與i的值進行比較。調試器是你最好的朋友。