-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。
它是'字符串子字符串(int startIndex,int length)',但不是'字符串子字符串(int startIndex,int endIndex)'。 – PetSerAl
爲什麼不使用string.Split呢? (順便說一下,Substring的第二個參數是要檢索的字符數,而不是最後一個檢索的字符的位置) – Steve
我們沒有在我們的教科書中使用string.split,所以我嘗試瞭解如何在不分割的情況下解決問題。無論如何謝謝你的回答,事實證明這是問題所在。 – hjsv41