复杂内容的遍历
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 14 课,共 66 课。
遍历嵌套数组等复杂结构需要采用特殊方法。
使用嵌套循环遍历二维数组:
int[][] matrix = new int[3][];
matrix[0] = new int[] { 1, 2, 3 };
matrix[1] = new int[] { 4, 5, 6 };
matrix[2] = new int[] { 7, 8, 9 };
for (int i = 0; i < matrix.Length; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
Console.WriteLine(matrix[i][j]);
}
}逐个遍历字符串数组并处理每个字符:
string[] words = { "hello", "world" };
for (int i = 0; i < words.Length; i++)
{
for (int j = 0; j < words[i].Length; j++)
{
Console.WriteLine(words[i][j]);
}
}统计交错数组中的元素数量:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6 };
int totalItems = 0;
for (int i = 0; i < jaggedArray.Length; i++)
{
totalItems += jaggedArray[i].Length;
}
Console.WriteLine($"Total items: {totalItems}");挑战
简单创建一个名为 countElements 的方法,它:
- 接收一个字符串交错数组(string[][])作为参数
- 统计整个交错数组中的元素数量
- 返回元素总数
例如,给定:
[
["apple", "orange", "apple"],
["banana", "apple"],
["orange"]
]结果应为 6(3 + 2 + 1)。
亲手试试
using System;
public class CountElements
{
// 实现 countElements 方法
public static int countElements(string[][] nestedArray)
{
// 在这里编写你的代码
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器