2016-12-18 63 views
-1

我試圖用Substring()分割一個字符串,我遇到了一個問題,我不斷收到與certin值崩潰。有問題的通道是(根據「調試」我試過):String.Substring()與某些輸入崩潰

string sub = str.Substring(beg,i); 

和整個代碼是:

static void Prints(string str) 
    { 
     int beg = 0; 
     for (int i = 0; i < str.Length; i++) 
     { 
      if (str[i] == '*') 
      { 
       Console.WriteLine(i); 
       //Console.WriteLine("before"); 
       string sub = str.Substring(beg,i); 
       //Console.WriteLine("after"); 
       beg = i+1; 

       if (sub.Length % 2 == 0) 
       { 

        Console.WriteLine(sub.Length/2); 
        int n = sub.Length/2; 
        Console.WriteLine("{0} {1}", sub[n-1], sub[n]); 
       } 
       else 
       { 
        int n = sub.Length/2; 
        Console.WriteLine(sub[n]); 
       } 

當輸入的eror發生:

hi*its* 

多數民衆贊成在輸出:

h i 


Unhandled Exception: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. 
Parameter name: length 
    at System.String.Substring(Int32 startIndex, Int32 length) 
    at _39.Program.Prints(String str) in D:\12\39\Program.cs:line 36 
    at _39.Program.Main(String[] args) in D:\12\39\Program.cs:line 13 

我知道可能有更好的方式使用split(),但我仍然想明白是什麼導致eror。 在此先感謝 Doron。

+6

它是'字符串子字符串(int startIndex,int length)',但不是'字符串子字符串(int startIndex,int endIndex)'。 – PetSerAl

+1

爲什麼不使用string.Split呢? (順便說一下,Substring的第二個參數是要檢索的字符數,而不是最後一個檢索的字符的位置) – Steve

+0

我們沒有在我們的教科書中使用string.split,所以我嘗試瞭解如何在不分割的情況下解決問題。無論如何謝謝你的回答,事實證明這是問題所在。 – hjsv41

回答

1

問題是,你沒有從總長中減去你到字符串中的距離。 如果你看調試輸出,你會發現:

str.Substring(3, 1) = "i" 
str.Substring(3, 2) = "it" 
str.Substring(3, 3) = "its" 
str.Substring(3, 4) = "its*" 
str.Substring(3, 5) = // Error! You're beyond the end of the string. 

讓您明明白白試圖拉(在你的例子)從字符串6個字符開始位置3.這將需要總輸入字符串長度爲10或更多(因爲子串是基於零指數的)。您的輸入字符串只有7個字符。

嘗試標記您的字符串。只要您嘗試使用索引手動標記化並計算出錯的地方。 Tokenizing是一個神發送:) 祝你好運!