foreach迭代遍歷
語法規則如下:
注意:迭代遍歷是隻讀的,不能修改
//foreach性能消耗要⼤⼀點,所以能⽤for的儘量⽤for
foreach (var item in number)
{
Console.WriteLine(item);
//迭代遍歷是隻讀的,不能寫⼊
//item = 1;
}
⽤foreach遍歷字符串,求字符串中包含⼏個n 字符
//定義字符串
string str01 = "Hello,csdn!";
//定義計數器
int count01 = 0;
foreach (var item in str01)
{
if (item == 'n')
{
count01++;
}
}
Console.WriteLine("該字符串中有{0}個‘n’字符。", count01);
有疑問的可以私信博主。
點個關注,給個讚唄!