猿问

求,详细讲解foreach循环的用法,急!

foreach( 这里的参数具体什么意思啊? )
{ ...
}

比如说 我想找一个 字符 在不在一个字符数组 char[] args 里.

UYOU
浏览 227回答 3
3回答

慕尼黑8549860

foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。能够应用的编程语言类别:Java、C# 、PHP、D语言(Phobos库)。foreach语句是c#中新增的循环语句,他对于处理数组及集合等数据类型特别方便。foreach语句的一般语法格式如下:foreach(数据类型 标识符 in 表达式){循环体}。C# 示例:12345int[]arr=newint[]{0,1,2,3,4};foreach(int i in arr){Console.Write(i);}JAVA示例:1234int[] a = {1,2,3};for(int i : a)System.out.print(i + ",");}

长风秋雁

foreach(char arg in args)//"char"是args里面每个元素的类型,arg就是从args里面提取出的“char”类型的一个元素,in是关键字,args就是你要操作的集合类型数据。其实和for()循环类似,只是不需要记录循环步数,同时,在foreach过程中,args是不允许被改变的。{if(arg == ch){//存在}else{//不存在}) 

摇曳的蔷薇

using System;namespace Example_6{/// <summary>/// 此程序演示如何使用 foreach 循环。/// </summary>class DigitLetterPunctuation{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(string[] args){// 存放字母的个数int countLetters = 0;// 存放数字的个数int countDigits = 0;// 存放标点符号的个数int countPunctuations = 0;// 用户提供的输入string input;Console.WriteLine("请输入一个字符串");input = Console.ReadLine();// 声明 foreach 循环以遍历// 输入的字符串中的每个字符。foreach(char chr in input){// 检查字母if(char.IsLetter(chr))countLetters++;// 检查数字if(char.IsDigit(chr))countDigits++;// 检查标点符号字符if(char.IsPunctuation(chr))countPunctuations++;}Console.WriteLine("字母的个数为: {0}", countLetters);Console.WriteLine("数字的个数为: {0}", countDigits);Console.WriteLine("标点符号的个数为: {0}", countPunctuations);}}}
随时随地看视频慕课网APP

相关分类

Python
我要回答