![](/img/trans.png)
[英]How to trim each string element in the string array without using loop?
[英]How to loop through string array and add each element to object array
我試圖遍歷一個名為string[] splitWords
的字符串數組。 數組采用以下格式:
// Write your main here
Write("Enter a number between 1 & 10: ");
int input = Convert.ToInt32(ReadLine());
Random ranNumberGenerator = new Random();
int randomNumber;
randomNumber = ranNumberGenerator.Next(1, 11);
if (input == randomNumber)
{
WriteLine("correct");
}
else if (input < randomNumber)
{
WriteLine("too low");
}
else
{
WriteLine("too high");
}
我目前正在嘗試遍歷該數組,該數組將每個元素分別拆分並分配給對象數組。 例如,需要在自己的對象數組元素中以此類推(每3個元素)。 因此,對象數組中總共有5個元素。 目前,我的代碼無法正常工作,或給我任何錯誤。
// Write your main here
Write("Enter a number between 1 & 10: ");
int input = Convert.ToInt32(ReadLine());
Random ranNumberGenerator = new Random();
int randomNumber;
randomNumber = ranNumberGenerator.Next(1, 11);
if (input == randomNumber)
{
WriteLine("correct");
}
else if (input < randomNumber)
{
WriteLine("too low");
}
else
{
WriteLine("too high");
}
使用LINQ將使此任務非常容易:
Station[] stationNames = splitWords
.Select(word => word.Split(' '))
.Select(a => new Station(a[0], a[1], a[2]))
.ToArray();
您的代碼已經關閉,您需要做的就是刪除if
塊
代替:
stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
if (stationCounter % 3 == 0)
{
stationCounter++;
}
您只需要:
stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
stationCounter++;
因為循環的每次迭代都會移動3個增量,所以您每次只需要遞增while計數器即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.