簡體   English   中英

指數數組的邊界之外

[英]Index was outside the bounds of the array

很簡單的問題,但還是無法解決。

我將消息傳遞給數組

feet nimantha 1 2 3 4 5 6 7 8 120827

我已經像這樣聲明了數組,

string[] arr1 = new string[10];

在那之后,我嘗試了

string[] arr1 = new string[11];

但兩者都向我展示了這個異常 - Index was outside the bounds of the array

代碼在這里。

protected void Page_Load(object sender, EventArgs e) {
  try {
    string mobileNo = Request.QueryString["msisdn"];
    int  dest = int.Parse(Request.QueryString["shortcode"].ToString());
    string messageIn = Request.QueryString["msg"];
    string operatorNew = Request.QueryString["operator"];

    // Label1.Text = "ok";
    WriteToFile(mobileNo, dest, messageIn, operatorNew);
    if (messageIn != null) {
      string[] arr1 = new string[11];
      arr1 = messageIn.Split(' ');
      int size = arr1.Length;
      string arrmsg = "";
      foreach (string _element in arr1) {
        if (arrmsg == "")
          arrmsg = _element;
        else {
          arrmsg = arrmsg + "/" + _element;
        }
      }
    }
  } catch {}
}

(在問題中添加了更多代碼時進行了編輯):

嘗試替換這個:

string[] arr1 = new string[11]; 
arr1 = messageIn.Split(' ');

具有以下內容:

string[] arr1 = messageIn.Split(new char[]{' '});

這很可能會導致數組長度超過 11,但這並不重要 - 在此處填充數組之前無需指定長度。

我認為您將其與字符數組混淆了。 在你的情況下,我會簡單地做:

arr1[0] = "feet nimantha 1 2 3 4 5 6 7 8 120827";

如果這不是您想要的,請參閱 Kjartan。 Sry,我寫的是錯誤的,代碼是在我寫完之后來的。 :(

如果你需要的結果是

arrmsg = "feet/nimantha/1/2/3/4/5/6/7/8/120827"

並且您有例外,因為您的字符串數組 arr1 的長度與帶有空格的字符串 Split 結果不匹配,那么您可以聲明並分配您的字符串數組來存儲字符串 Split 結果

//string[] arr1 = new string[11];
string[] arr1 = messageIn.Split(' ');

然后 arr1 可以根據字符串拆分結果具有不同的數組大小。 例如,

string messageIn ="feet nimantha 1 3 4 5 6 7 8 120827";
//arr1 is string[10] here
string[] arr1 = messageIn.Split(' ');

messageIn = "feet nimantha 1 3 4 5 6 7 8 120827 2132144";
//arr1 is string[11] here
arr1 = messageIn.Split(' ');

因此您不必擔心字符串數組 arr1 的大小與字符串拆分的結果不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM