我正在學習我的第一次 C# 測驗(初學者)。我有一個問題,我應該使用回圈創建一個新陣列。例如,這個任務的任務是撰寫一個接收句子(字串)和字母(字符)的方法。然后,該方法必須確定字母出現在句子中的哪些索引位置,然后將這些位置放入陣列中。例如,我們有一個短句“Hello world!” 和字母 'o' 那么陣列應該包含 4(第一個實體的索引位置)和 7(第二個實體的索引位置)。
我不允許使用除 .Length、Console.WriteLine 之外的內置方法。
你可以在下面看到我的代碼。它根本不起作用。我希望它列印出“4, 7,”
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i )
{
Console.Write(result[i] ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i )
{
if(sentence[i] == letter)
{
newArr[count] = i;
count ;
}
}
return newArr;
}
uj5u.com熱心網友回復:
Length問題是您事先不知道陣列。所以你必須計算 count然后才創建陣列:
static int[] IndexesOfChar(string sentence, char letter)
{
// Required array length computation:
int count = 0;
for (int i = 0; i < sentence.Length; i )
if (sentence[i] == letter)
count ;
// We know count, we are ready to create the array:
int[] newArr = new int[count];
// Finally, we fill in the array
// let do not re-use count, but declare separate index variable
int index = 0;
for (int i = 0; i < sentence.Length; i )
if (sentence[i] == letter)
newArr[index ] = i;
return newArr;
}
您的任務不是陣列的好例子,通常我們List<T>在不知道大小時放置:
using System.Linq;
...
static int[] IndexesOfChar(string sentence, char letter) {
List<int> result = new List<int>();
for (int i = 0; i < sentence.Length; i)
if (sentence[i] == letter)
result.Add(i); // <- unlike array we can just Add a new item
// create an array from list with a help of Linq
return result.ToArray();
}
uj5u.com熱心網友回復:
它不起作用,因為在方法IndexesOfChar中,您創建了一個長度為count的陣列(即在該點為零)。一旦宣告了陣列,就不能修改它的長度。
如果您不能使用任何內置方法,我建議您將 newArr 宣告為list。這就是您應該填充索引的內容,然后創建一個陣列,并使用另一個 for 回圈將串列的值填充到該陣列中。
uj5u.com熱心網友回復:
與 type 不同List,您無法更改陣列的大小,因此無法更改,newArr[count] = i;因為 的大小newArr為 0。相反,如果您只想使用陣列,則可以 newArr使用其舊值 新整數重新分配:
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i )
{
Console.Write(result[i] ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i )
{
if(sentence[i] == letter)
{
var updateArr = new int[newArr.Length 1];
for (int j = 0; j < newArr.Length; j )
{
updateArr[j] = newArr[j];
}
updateArr[newArr.Length] = i;
newArr = updateArr;
count ;
}
}
return newArr;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521941.html
標籤:C#数组for循环返回
