除 ISO/IEC C++ 中定义的3种循环语句以外,C++/CLI 还提供了for each 语句。在C++/CLI 中,for each 循环的效率比其他几种形式的循环效率更高。
#include"stdafx.h"
using namespace System;
int main(array <System::String ^> ^args)
{
int vowels(0), consonants(0);
String^ proverb(L"A nod is as good as a wink to a blind horse.");
for each(wchar_t ch in proverb)
{
if(Char::IsLetter(ch))
{
ch = Char::ToLower(ch);
switch(ch)
{
case 'a': case 'e': case 'i': case 'o': case 'u':
++vowels;
break;
default:
++consonants;
break;
}
}
}
Console::WriteLine(proverb);
Console::WriteLine(L"The proverb contains {0} vowels and {1} consonants.", vowels, consonants);
Console::ReadLine();
return 0;
}
该程序计算变量proverb引用的字符串中元音和辅音的个数,方法是使用for each 循环重复处理字符串中的各个字符。