C# 《五》流程控制(2)

1、迭代语句之 foreach 语句

1、foreach提供了一个 for 语句的捷径,而且还促进了集合类更为一致。

2、格式:

for(初始值;判断条件;增长值)
{
    代码体;
}

 

foreach(类型  变量  in 集合)
{
     代码体;
}

补充:string 类型可以看成是 char 类型的一个集合
          string 字符串 char 字符

      My name is snowskywalker

 

例题:

   根据你输入的英文句子,程序实现句中各单词逐行输出到屏幕上;

 

2、新语句。

char.IsWhiteSpace(c);


3、foreach 语句

每执行一次内含的代码时,循环变量就会依次读取集合中的一个元素。

此处的循环变量只是一个读型的局部变量,这个值如果被修改编译器会发生错误。

 

程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5._8迭代语句之foreach
{
    class Program
    {
        static void Main(string[] args)
        {
            //for(int i = 1;i <= 50;i++)
            //{
            //    Console.WriteLine(i);
            //}
            //for (int i = 0; i <= 50; i++)
            //{
            //    Console.WriteLine(i);
            //}
            //将语句识别为单词并逐行输出
            //语句用string 类型,字母用char
            Console.WriteLine("请您输入一个英文句子:");
            string str = Console.ReadLine();
            Console.WriteLine("您输入的句子包含一下的单词:");
            foreach (char word in str)
            {
                if(char.IsWhiteSpace(word))
                {
                    Console.WriteLine();
                }
                else
                {
                    Console.Write(word);
//word = 't'; //foreach语句的迭代变量不允许重新赋值 } } Console.ReadKey(); } } }

运行结果:

 

posted @ 2017-09-09 14:21  让优秀成为一种习惯  阅读(173)  评论(0编辑  收藏  举报