3 回答

TA貢獻1818條經驗 獲得超11個贊
foreach 語句為數組或對象集合中的每個元素重復一個嵌入語句組。foreach 語句用于循環訪問集合以獲取所需信息,但不應用于更改集合內容以避免產生不可預知的副作用。
能夠應用的編程語言類別:Java、C# 、PHP、D語言(Phobos庫)。
foreach語句是c#中新增的循環語句,他對于處理數組及集合等數據類型特別方便。
foreach語句的一般語法格式如下:
foreach(數據類型 標識符 in 表達式)
{
循環體
}。
C# 示例:
12345 | int []arr=newint[]{0,1,2,3,4}; foreach ( int i in arr) { Console.Write(i); } |
JAVA示例:
1234 | int [] a = { 1 , 2 , 3 }; for ( int i : a) System.out.print(i + "," ); } |

TA貢獻1757條經驗 獲得超7個贊
foreach(char arg in args)//"char"是args里面每個元素的類型,arg就是從args里面提取出的“char”類型的一個元素,in是關鍵字,args就是你要操作的集合類型數據。其實和for()循環類似,只是不需要記錄循環步數,同時,在foreach過程中,args是不允許被改變的。
{
if(arg == ch)
{
//存在
}
else
{
//不存在
}
)

TA貢獻1793條經驗 獲得超6個贊
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);
}
}
}
添加回答
舉報