一、C#上位机语法篇学习笔记

0、基础中的基础

Write和WriteLine方法对比

#region  1 Write和WriteLine方法对比
 static void Test1()//方法
 {
     string emal1 = "[email protected]";
     string userName = emal1.Substring(0, 7);
     Console.WriteLine(userName);//输出后换行

     string userName1 = emal1.Substring(0);//第0个开始到最后
     Console.WriteLine(userName1);//输出后换行
     Console.Write("请输入姓名");
     Console.WriteLine(emal1);//输入CW按Tab可快速输入此代码
     
 }
 #endregion

小结:WriteLine(userName1);//输出后换行,Write(“请输入姓名”);//输出不换行

基本输入ReadLine方法

#region 2 基本输入ReadLine方法
 static void Test2()
 {
     Console.Write("请输入姓名:");
     string name = Console.ReadLine();//ReadLine从控制台读取的数据返回的是字符串格式 //Read读取控制台返回整数型

     Console.WriteLine("请输入学员成绩");
     int score = int.Parse(Console.ReadLine());//int.Parse 字符串转换成整数

     Console.WriteLine("姓名:"+name + "     成绩:"+score);//字符串为目标的可以使用int型变量数据,不需要转换
     string result = "姓名:" + name + "     成绩:" + score;//字符串为目标的可以使用int型变量数据,不需要转换
     Console.WriteLine(result);
     //int result ="成绩"+ score; 这样以整型为目标写入字符串是不可以的
 }
 #endregion

小结:
Read 方法通常用于二进制文件或当需要逐个字符读取时,返回的是整型
ReadLine 通常用于文本文件,因为它允许一次读取一整行,返回的是字符串型

字符串简写格式化

 #region 3 字符串简写格式化
 static void Test3()
 {
     Console.Write("请输入姓名:");
     string name = Console.ReadLine();//ReadLine从控制台读取的数据返回的是字符串格式 //Read读取控制台返回整数型

     Console.WriteLine("请输入学员成绩:");
     int score = int.Parse(Console.ReadLine());//int.Parse 字符串转换成整数

     Console.WriteLine("请输入班级:");
     string className = Console.ReadLine();

     string result = "姓名:" + name + "     成绩:" + score + "     班级:"+className;
     Console.WriteLine(result);

     string result1 = string.Format("姓名:{0}  成绩:{1}  班级:{2}", name, score, className);//Format格式化字符串方法

     Console.WriteLine(result1);

     string result2 = $"姓名{name}成绩{score}班级{className}";//推荐用的字符串格式化方法
     Console.WriteLine(result2);

     Console.WriteLine($"姓名{name}成绩{score}班级{className}");//WriteLine自带格式化方法,所以也可直接写成这样
     Console.WriteLine("姓名:{0}  成绩:{1}  班级:{2}", name, score, className);//和这样
 }
 #endregion

小结:注意:string.Format格式化字符串方法的存在(虽然大概目前感觉没啥用)
注意:""里面的(除了{})其他都是字符串,包括空格都是有数据的字符串(先这么理解)

赋值和算数运算的使用

 #region 4 赋值和算数运算的使用
 static void Test4()
 {
     int a = 10;
     int b = 20;
     int c=a*(a+b)/b;
     int d = c%a;//先除,取余数
     
     Console.WriteLine($"a*(a+b)/b={c}  c%a= {d}");//先算括号内,然后从左到右。 

     Console.WriteLine($"a++ ={a++}  --b ={--b}");//a++在WriteLine里显示之后+1 ,--b在WriteLine里显示之前-1    

 }
 #endregion

小结:a++ 后+1 ,++a先+1

比较运算符分析

#region 5 比较运算符分析
 static void Test5()
 {
     string name = "song";
     string name1 = "peng";
     string name2 = "song";
     bool result = name.Equals(name1);//Equals 是方法 的一种比较 此处还不是当前要学的
     Console.WriteLine(result);

     Console.WriteLine(name==name2);//字符串比较
     Console.WriteLine(name1!=name2);

     Console.WriteLine("----------------------------");

     int a = 10;
     int b = 20;
     int c = 18;

     Console.WriteLine(a>b);//整数比较
     Console.WriteLine(b>c);
     Console.WriteLine(a==c);
 }
 #endregion

小结:变量名.后面的 都是方法

1、值类型之间转换

值类型之间 自动类型转换

 #region 1 值类型之间 自动类型转换
 static void Test1()
 {
     double a = 100.5;
     int b = 50;
     double result = a + b;//带小数点的类型比整型更精,更“大”所以可以直接把整型int数据加到double里存为double,属于自动类型转换
     Console.WriteLine($"自动类型转换结果:{result}");//如果int和double计算,目标结果存储的类型不能为int,因为大的不能共存到小的里面。如果必须那样,就需要强制类型转换了
 }
 #endregion

小结:位数多的(包括小数点位数)存位数小的值类型就是属于自动类型转换。

值类型之间 强制类型转换

#region 值类型之间 强制类型转换
static void Test2()
{
    double a = 100.5;
    int b = 50;
    int result = (int)a + b;//把整型int数据加到double里存为int,先把double类型的a强制类型转换成int类型
    Console.WriteLine($"强制类型转换结果:{result}");//如果int和double计算,目标结果存储的类型不能为int,因为大的不能共存到小的里面。如果必须那样,就需要强制类型转换了
}
#endregion

小结:如果硬要把大的硬塞进小的里面,就要在大的前面加(要变成的模样)告诉这个大的你必须要减肥,变成括号里那样细小,才能和其他细小同类配合,塞进一个窝里去。

值类型之间 强制类型转换object

 #region 值类型之间 强制类型转换object 
 static void Test3()
 {
     object a = 100.5;
     int b = 50;
     int result = (int)(double)a + b;//object属于引用类型,所以要先把object转换成double,然后再把double转换成int
     Console.WriteLine($"强制类型转换结果:{result}");//如果int和double计算,目标结果存储的类型不能为int,因为大的不能共存到小的里面。如果必须那样,就需要强制类型转换了
 }
 #endregion

小结:引用类型object牛逼,先转成等量数据的值类型double,才能再把带小数点的值类型double强制转换成 int

字符串和值类型间强制类型转换 字符串转数值

#region 2 字符串和值类型之间 强制类型转换 字符串转数值
static void Test4()
{
    double a = double.Parse("100.1");
    int b = int.Parse("100");
    float c= float.Parse("100.2");
    double d = (int)double.Parse("10.5");//先字符串转double数值,然后double转int,最后赋值给double类型的d
    DateTime t1 = DateTime.Parse("2024-8-24");//默认显示日期和时间0:00:00
    Console.WriteLine($"{a}    {b}    {c}    {d}    {t1}");

}
#endregion

小结:字符串是什么类型数值(字符串内容必须是数值),就要用对应的 . 方法转换成对应的值类型。如果这个值类型不是想要的可以再次强制转换。

字符串和值类型间强制类型转换 数值转字符串

 #region  字符串和值类型之间 强制类型转换 数值转字符串
 static void Test5()
 {
     int a = 100;
     double b = 1.2;

     string s1=a.ToString();
     string s2=b.ToString();
     Console.WriteLine($"{a}  {b}");
 }
 #endregion

小结:值变量.ToString() 就变成字符串咯

强制类型转换 万能转换器

#region 3 强制类型转换 万能转换器
 static void Test6()
 {
     double a = Convert.ToDouble("10.7");
     int b = Convert.ToInt32(a);//double类型的变量放入int类型万能转换器转换10.7为四舍五入的11
     int d = (int)Convert.ToDouble("15.8");//double类型的字符写到万能转换器后要强制转换成int才能传给int类型的变量d,但小数点后面的被强制消除了结果为15
     float c = Convert.ToSingle(12.1);//注意float对应的万能转换是Single
     DateTime t1 = Convert.ToDateTime("2024-8-24");
     Console.WriteLine($"{a}   {b}  d:{d}  {c}    {t1}");//默认显示日期和时间0:00:00
 }
 #endregion

小结:Convert是转换的意思,小数的变量经万能转换器转成整数是会四舍五入的

2、程序逻辑

if条件选择与逻辑运算符

 #region 1 if条件选择与逻辑运算符
 static void Test1()
 {
     Console.Write("请输入姓名:");
     string Name = Console.ReadLine();//ReadLine读取控制台一行返回字符型
     Console.Write("请输入密码:");
     string Pwd = Console.ReadLine();
     //int Pwd = Console.Read();//Read读取控制台返回整数型
     
     
     if (Name == "" || Pwd == "") //if (Name == null || Pwd == "")//因为控制台上是字符类型所以永远都不为空null,这样写是错误的
     {
         Console.WriteLine("密码和姓名不能为空");
       //  return;//无条件退出此方法,不再执行下面
     }
     if (Name == string.Empty || Pwd == string.Empty) //string.Empty和""效果是一样的。注意""中间不可以加空格
     {
         Console.WriteLine("密码和姓名不能为空");
        // return;//无条件退出此方法,不再执行下面
     }
     if (Name.Length==0 || Pwd.Length == 0) //测量字符串长度,如果为0就说明没填,注意输入不能为空值,所有字符串都有Length属性
     {
         Console.WriteLine("密码和姓名不能为空");
         return;//无条件退出此方法,不再执行下面
     }

     if (Name == "陈浩南" && Pwd == "123456")
     {
         Console.WriteLine("吾皇万岁万岁万万岁");
         Console.WriteLine("请输入身份");
         bool shenfen = Convert.ToBoolean(Console.ReadLine());//把控制台的字符类型万能转换成bool类型,赋值给变量shenfen

         if (shenfen == true)
         {
             Console.WriteLine("大佬真牛逼");
         }
         if (shenfen== false)
         {
             Console.WriteLine("大佬帅呆了");
         }
     }
 }
 #endregion

小结:string.Empty= “” 但≠null
所有字符串变量都有.Lenth 返回值为字符串长度

复杂if与运算符优先级策略

#region 2 复杂if与运算符优先级策略
static void Test2()
{
    //考试分数优秀条件1 笔试>=80 且 机试>=90
    //考试分数优秀条件2 笔试==100 且 机试>60 或者 机试==100 且 笔试>60

    Console.WriteLine("请输入笔试成绩:");
    int writScore = Convert.ToInt32(Console .ReadLine());
    Console.WriteLine("请输入机试成绩:");
    int labScore = Convert.ToInt32(Console .ReadLine());

    if (writScore>=80 && labScore>=90)
    {
        Console.WriteLine("我是优秀学生");
    }
    else
    {
        Console.WriteLine("我不是优秀学生");
    }
    if ((writScore == 100 && labScore > 60) || (writScore > 60 && labScore == 100))//括号括起来的最优先级。
    {
        Console.WriteLine("我偏科,但我依然优秀");
    }
    else
    {
        Console.WriteLine("我严重偏科,不及格");
    }
    string a = writScore < 60 && labScore < 60 ? "我是坏学生" : "我是好学生";//三元表达式,if和else的简写
    Console.WriteLine($"{a}");

    
    
    int b = 1,c=5,d=8,e=3;
    if(b>c)
    {

    }
    if(b < e)
    {
        Console.WriteLine("假如到这判断完毕得到结果,但下面的if依然会运行");
    }//如果想判断得到想要的结果后就不再执行接下来的其他if,就要用到if和多个if else了  为多条件选择。
    if (b<d)
    {

    }           
}
#endregion

小结:if if else if else if else… else
如果 否则如果 否则如果 否则如果…否则
从上到下依次判断
第一个是if,接下来都是if else ,最后一个判断是else

if嵌套 不建议超过三层

#region if嵌套 不建议超过三层
 static void Test7()
 {
     Console.WriteLine("请输入要消费的金额:");
     int totaMoney = Convert.ToInt32(Console .ReadLine());
     Console.WriteLine("请输入会员类型");
     string vip = Convert.ToString(Console .ReadLine());

     if (totaMoney < 2000)
     {
         Console.WriteLine($"请付款{totaMoney*0.8}");
         if (vip=="普通")
         {
             Console.WriteLine($"赠送十元代金卷");
         }
         else 
         {
             Console.WriteLine($"VIP赠送五十元代金卷");
         }
     }
     else if(totaMoney >=2000 && totaMoney < 3000)
     {
         Console.WriteLine($"请付款 {totaMoney * 0.7}");
         if (vip == "普通")
         {
             Console.WriteLine($"赠送五十元代金卷");
         }
         else
         {
             Console.WriteLine($"VIP赠送一百元代金卷");
         }
     }
     else if (totaMoney >=3000 && totaMoney<4000)
     {
         Console.WriteLine($"请付款{totaMoney * 0.6}");
         if (vip == "普通")
         {
             Console.WriteLine($"赠送一百元代金卷");
         }
         else
         {
             Console.WriteLine($"VIP赠送二百元代金卷");
         }
     }
     else
     {
         Console.WriteLine($"请付款{totaMoney*0.5}");
         if (vip == "普通")
         {
             Console.WriteLine($"赠送二百元代金卷");
         }
         else
         {
             Console.WriteLine($"VIP赠送五百元代金卷");
         }
     }

 }
 #endregion

小结:嵌套不建议超过三层。

switch分支结构的应用

#region  switch分支结构的应用
static void Test8()
{
    int a = 1, b = 2, c = 3;
    int d = 0;
    Console.Write($"请输入答案:");
    d = Convert.ToInt32(Console.ReadLine());
    switch (d)
    {
        case 6: 
            Console.WriteLine("a*b*c=6");
            break;
        case 7:
            Console.WriteLine("a*b*c=7");
             break;
        case 8:
            Console.WriteLine("a*b*c=8");
             break;
        default:    //没找到以上的匹配值
            Console.WriteLine("没有此答案");
             break;
    }
 }
#endregion

小结:switch分支结构 如果选项有符合条件的,直接跳到符合条件处执行,完毕后退出。不像if判断那样每条依次判断。所以switch节省时间。
注意:判断的内容只能是一个,不能是复杂的
switch支持判断的类型有:
整数类型( sbyte , byte , short , ushort , int , uint , long , ulong )
字符类型( char )
枚举类型( enum )
字符串类型( string ,从 C# 7.0 开始支持)
布尔类型( bool ,从 C# 7.0 开始支持)
固定大小的数值类型( float , double , decimal ,从 C# 7.3 开始支持)

3、循环结构

for循环 固定次数循环

#region 1 for循环 固定次数循环
 static void Test1()
 {
    
     Console.WriteLine("请输入测量次数");
     int cishu = int.Parse (Console.ReadLine());//s将输入的字符串转换成int再赋值给int类型的cishu变量
     for (int i = 0; i < cishu; i++)
     {
         int shuzhi = 0;
         Console.WriteLine($"第{i+1}次测量结果");
         for (int b = 0; b < 3; b++)
         {
             
             shuzhi += int.Parse(Console.ReadLine());
             if (b == 2)
             {
                 shuzhi = shuzhi / 3;
                 Console.WriteLine($"本次测量结果为{shuzhi}");
             }
         }
     }
 }
 #endregion

小结:
for(定义变量并赋值(只一次);判断然后执行函数体;变量值++)

while 不固定循环,不确定次数情况用while

#region 3 while 不固定循环,不确定次数情况下使用while
static void Test2()
{
    for (int a=0; a < 3; a++)
    {
        int count = 0;
        while (count<6)
        {
            Console.WriteLine("此瓶是否合格?Y/N,1/0");
            string ok = Console.ReadLine();
            if (ok=="Y" || ok=="1")
            {
                count++;
                Console.WriteLine("放入箱中");
            }
            else
            {
                Console.WriteLine("此瓶不合格");
            }
        }

        Console.WriteLine($"已完成{a+1}箱");
        if (a == 2)
        {
            Console.WriteLine($"全部完成{a + 1}");
        }
    }

}
#endregion

小结:while(为真,或符合条件就循环)

while循环嵌套案例分析与实现,不确定次数情况下使用while

#region 4 while循环嵌套案例分析与实现,不确定次数情况下使用while
  static void Test3()
  {
      int add = 0;
          while (true)
          {
          int count = 0;
            while(count<6)
          {
              Console.WriteLine("此产品是否合格?");
             int a =int.Parse(Console.ReadLine());
              if (a==0)
              {
                  Console.WriteLine("此瓶不合格");
                  continue;//不再向下执行,跳到循环开始位置执行,(结束本次循环,执行下一次循环)
              }
              count++;
              Console.WriteLine($"当前箱内瓶数:{count}");
          }
          add++;
          Console.WriteLine($"当前为第{add}箱是否继续?");
          if(Console.ReadLine()=="N")
          {
              Console.WriteLine($"打包已完成,共{add}包");
              break;//结束当前层循环,跳出当前层死循环while (true)
          }

          //不再打包的跳出条件
      }
  }
  #endregion

小结:continue;中止并跳到当前层循环开头重新循环
break;//结束当前层循环,跳出当前层循环

do while循环嵌套案例分析与实现,先执行后判断

 #region 5 do while循环嵌套案例分析与实现,不确定次数情况下使用while
 static void Test4()
 {
     int a = 0;
     int b = 0;
     do //do while 和 whlie区别就是一个先执行数据,然后判断是否继续,最少执行一遍。一个是先判断,后执行数据操作,可以一遍都不执行数据操作
     {
         a++;
         Console.WriteLine($"a={a}");
         do
         {
             if (Console.ReadLine() == "N") 
             {
                 Console.WriteLine("退出");
                 break;
             }
             else
             {
                 b++;
                 Console.WriteLine($"b={b}");
             }
         } while (true);
     } while (true);
 }
 #endregion

小结:do while先执行后判断

4、字符串

字符串单个字符位置查询和总长度查询

 #region 1字符串单个字符位置查询和总长度查询
    static void Test1()
    {
        string name = "烧鸡";
        string email = "[email protected]";
        int index = email.IndexOf("@");//IndexOf 从0开始数位数,不管中文,英文,空格,符号,都是占1位
        int index1 = email.IndexOf("qq.com");//IndexOf 从0开始数位数,不管中文,英文,空格,符号,都是占1位,输入的字符串就返回这字符串第一个位的位数
        int index2 = email.IndexOf("qq.net");//如果搜索不到,就会返回错误代码"-1"
        int index3 = name.IndexOf("鸡");//IndexOf 从0开始数位数,不管中文,英文,空格,符号,都是占1位
        Console.WriteLine($"{index}    {index1}    {index2}     {index3}");

        int length = email.Length;//查出字符串总长度
        int length1= name.Length;//查出字符串总长度
        Console.WriteLine($"当前字符串长度email{length}    name{length1}");
        Console.WriteLine(email.Length  +  name.Length);//此种方法是两个长度整数加到一起结果显示出来
        Console.WriteLine($"{email.Length}   {name.Length}");//此种方法是两个长度整数分别显示
        Console.WriteLine(email.IndexOf("qq"));//只显示第一个q位置,为10
    }
    #endregion

小结:字符串变量名.IndexOf 从0开始到参数内字符串第一个字符数位数,不管中文,英文,空格,符号,都是占1位,输入的字符串就返回这字符串第一个位的位数
字符串名.Length;//查出字符串总长度

字符串截取

 #region 2字符串截取
    static void Test2()
    {
        string email = "[email protected]";

        string email1 = email.Substring(0, 9);// 读出第0位置开始长度9之内的字符串,注意:0参数是位置,9参数是读取长度
        string email2 = email.Substring(0, email.IndexOf("@"));//读出某个字符之前的所有字符串,读出@之前所有的
        string email3 = email.Substring(email.IndexOf("@")+1);//读出某个字符后面的所有内容,就是这个字符+1
        Console.WriteLine(email1);
        Console.WriteLine(email2);
        Console.WriteLine(email3);
    }
    #endregion

小结:字符串变量名.Substring(0, 9);// 读出第0位置开始长度9之内的字符串,注意:0参数是位置,9参数是读取长度。
长度参数可以利用 字符串变量名.IndexOf 从0开始到参数内字符串第一个字符数位数,这样就不用自己数位数了

字符串的比较

 #region 3 字符串的比较
    static void Test3()
    {
        string name = "song";
        string name1 = "zhang";
        string name2 = "peng";
        string name3 = "song";
        string name4 = "SOng";
        Console.WriteLine(name==name3);//相等字符串输出为True
        Console.WriteLine(name1==name2);//不相等字符串输出False
        Console.WriteLine("name==name3"+name==name3);//因为+和==优先级相同,所以是从左到右计算。所以"peng yv"+name不等于name3,不相等字符串输出False
       
        Console.WriteLine("name==name3" + (name == name3));//  ()上优先级就会显示为 peng yv" true了
        Console.WriteLine("name==name3"+name.Equals(name3));//对象name调用方法Equals时候,他的优先级是比较高的,所以不用加()

        Console.WriteLine("name==name4" + (name.ToLower() == name4.ToLower()));//字符串区分大小写,如果想无视大小写对比,就用ToLower方法全部转换成小写再对比就好了
                                                                               // == 和Equals方法默认只能比较 值类型 或者 字符串 类型,对象类型(引用类型)是不能使用这种方法比较的
        Console.WriteLine("********************************************************************");
        int a = 10, b = 20, c= 10;
        Console.WriteLine("a==c" + (a==c));  
        Console.WriteLine("b==c  {0}",b==c);//前面的知识哦
        Console.WriteLine("b==c"+b.Equals(c));
    }
    #endregion

小结:注意优先级,不确定就加括号,相等字符串返回字符串True,不相等字符串返回字符串False

字符串格式化的拓展

#region 4 字符串格式化的拓展
static void Test4()
{
    string name = "song";
    int age = 340000;
    Console.WriteLine("学员姓名:{0}    学员年龄:{1:C}",name,age);//为了试验,我把年龄改成了金钱格式显示
    Console.WriteLine($"学员姓名:{name}    学员年龄:{age}");

    string info = string.Format("学员姓名:{0}    学员年龄:{1}", name, age);

    int money = 88888888;    //以下是金钱格式化
    string moneyType = string.Format("总金额:{0}", money);
    Console.WriteLine(moneyType);

  moneyType = string.Format("总金额:{0:C}", money);
    Console.WriteLine(moneyType);

    double sum = 58.88888888;//以下是保留小数点位数方法
    Console.WriteLine(sum.ToString("0.00"));//ToString将数值转换为等效的字符串形式,保留两位小数
    Console.WriteLine(sum.ToString("0.0000"));//保留四位小数
}
#endregion

小结:浮点类型变量名.ToString(“0.00”)将数值转换为等效的字符串形式,保留两位小数
其他的在字符串 $“{这里添加对应的符号就可以变为对应的格式}”

字符串的 空值 和 空对象的比较使用

 #region 5 字符串的 空值 和 空对象的比较使用

static void Test5()
    {
        string name = "";  //这个空值符串是占用空间的,它是有对象的
        string name1 = string.Empty;//同上,只是写法不一样

        Console.WriteLine(name.Equals(name1));
        Console.WriteLine("name的长度="+name.Length );
        Console.WriteLine("name1的长度=" + name1.Length);

        string name2;//没被赋值,程序会在编译报错
        string name3 = null;//空对象,因为是空的,不能使用对象的方法和属性,但它存在赋值的过程
        Console.WriteLine(name3==name);//空对象不等于空值
        // Console.WriteLine(name3 == name2);//这个编译时 会有语法错误,因为没赋值就使用
        //Console.WriteLine(name3.Equals(name));   会在运行后报错:未将对象引用设置到对象的实例。所以空对象不能使用对象的方法和属性 
        //空对象解决方法:首先找到哪个对象为null

        //判断字符串为空值优先使用方法推荐:
        //name.Length==0;
        //name1 == string.Empty;
        //name = "";
    }

    #endregion

小结:
“” 这个空值符串是占用空间的,它是有对象的
string.Empty;同""一样,只是写法不一样

string name2;//没被赋值,程序会在编译报错
string name3 = null;//空对象,因为是空的,不能使用对象的方法和属性,但它存在赋值的过程

字符串常用的其他方法( .后面的是方法)

#region 6 字符串常用的其他方法( .后面的是方法)
static void Test6()
{
    //字符串去空格的方法
    //去除前后空格
    string name = "   song   ";//注意这字符串的空格
    Console.WriteLine(name.Length);

    Console.WriteLine(name.Trim ());//去除空格后显示,但变量name内容没变,空格依然在
    Console.WriteLine(name.Trim().Length );//去除空格后测量字符串长度。注意这里同时使用了两次 .

    //大小写格式转换方法
    string name1 = "NAME";
    string name2 = "name";
    Console.WriteLine(name1.Equals(name2));//大写和小写对比
    Console.WriteLine(name1==name2.ToUpper ());//大写和小写变大写 对比是否相等
    Console.WriteLine(name1.ToLower ());//大写变小写
    Console.WriteLine(name2.ToUpper ());//小写变大写

    //获取字符串条件的最后一个索引位置
    string url = "[email protected]";
    Console.WriteLine(url.LastIndexOf("."));//0开始 第二个. 是第16位
}
#endregion
小结:
 Console.WriteLine(name.Trim ());//去除空格后显示,但变量name内容没变,空格依然在
字符串变量名.Trim().Length ;//去除空格后测量字符

Console.WriteLine(name1.ToLower ());//大写变小写
Console.WriteLine(name2.ToUpper ());//小写变大写

string url = “[email protected]”;
Console.WriteLine(url.LastIndexOf(“.”));//0开始数位 第二个. 是第16位

StringBuilder字符串的高效处理

 #region 7 StringBuilder字符串的高效处理
    static void Test7()
    {
        //普通字符串的拼接      这样并不高效,浪费内存
        string data = string.Empty;
        data += "AB";
        data += "CD";
        data += "EF";
        Console.WriteLine(data);

        Console.WriteLine("*****************************");
        //高效字符串的组合
        StringBuilder builder1 = new StringBuilder();
        builder1.Append("AB");
        builder1.Append("CD");
        builder1.Append("EF");

        string result = builder1.ToString();//对象转字符串类型,这样才能得到字符串类型变量
        Console.WriteLine(result);
        Console.WriteLine("********************************");

        builder1.Clear();//清空上面保存的字符串内容
        Console.WriteLine("还有没有:"+builder1.ToString());

        Console.WriteLine("**********************************");
        StringBuilder builder2 = new StringBuilder("本期课程信息:");//可以输入对象初始值
        string teacher = "宋老师";
        string month = "3个月";
        builder2.AppendFormat($"主讲老师:{teacher}   课程周期:{month}");//追加同时格式化
        Console.WriteLine(builder2.ToString());//也可以直接输出显示时候ToString

        Console.WriteLine("---------------------------");

        StringBuilder builder3 = new StringBuilder(".NET工控上位机和视觉应用发展势头迅猛!");
        builder3.Insert(0, "中国的");//在第0位添加插入 中国的  字符串。
        builder3.Insert(builder3.ToString().Length, "大家要加快学习速度!!!!");//转成字符串格式然后测长度,长度就是最后位置,插入字符串内容
        Console.WriteLine(builder3.ToString());

        Console.WriteLine("-------------------------------------");
        builder3.Remove(0,builder3 .ToString().IndexOf ("."));//位置0   到 .的长度位置,的字符串全都移除
        Console.WriteLine(builder3.ToString());

        Console.WriteLine("--------------------------------------");
        StringBuilder niubi = new StringBuilder("牛不不牛逼?");
        for (int i = 0; i < 3; i++)
        {
            niubi.Append(Console.ReadLine());
            Console.WriteLine(niubi.ToString());
        }
    }
    #endregion

小结:
.Append(“AB”);追加字符串
.ToString();//对象转字符串类型
.Clear();//清空
.AppendFormat($“主讲老师:{teacher} 课程周期:{month}”);//追加同时格式化
Console.WriteLine(builder2.ToString());//也可以直接输出显示时候ToString
.Remove(0,builder3 .ToString().IndexOf (“.”));//位置0 到 .的长度位置,的字符串全都移除

转义字符

 #region 8转义字符
    static void Test8()
    {
        // string path = "C:\DB\test.txt";//这样写\会红线报错
        string path1 = "C:\\DB\\test.txt";//双反斜杠为转义字符,代表一个\
        string path2 = @"C:\DB\CD\EF\WW\TT\H";//如果反斜杠太多,也可以在字符串”前加 @ 这样此字符串内所有\都可以正常输入
        //只有在C#变成会这样,\在字符串内不可单独输入,需要转义 \\  代表一个\。也可字符串外加@
        Console.WriteLine($"{path1}      {path2}");
    }
    #endregion 

小结:C#语言字符串""里面路径,网址等…两个\代表一个\

5、数组

数组

 #region 1 数组
 static void Test1()
 {
     int[] scores;//1声明数组  因为是空的所以不能打断点
     scores= new int[5];//2分配空间

     double[] scoreArray= new double[5];//实际开发中可以这样

     //3元素赋值
     scores[0] = 66;
     scores[1] = 77;
     scores[2] = 88;
     scores[3] = 99;
     scores[4] = 100;//最大下标数为4 ,不能写到5

     //4元素操作
     int avgScores = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) / 5;//求五个元素平均数
     Console.WriteLine(avgScores);
     //元素:存放的数据
     //下标:元素的索引,数组的索引 从0开始
     //类型:元素的数据类型
     //标识符:数组的名称
     int[] avgScore1 = new int[5] {1,2, 3, 4, 5};//下标和元素个数要一样,不然会报错
     int[] avgScore2= new int[] {1, 2, 3, 4,5};//可以不写下标(元素的索引),系统会自己查元素数量
     int[] avgScore3 = {1,2,3,4,5,6};//这个最简单,但上面的在特殊时候也能用得到
 }
 #endregion

小结:数组使用详细步骤:1声明数组 因为是空的所以不能打断点 2分配空间 3元素赋值 4元素操作
三种简写方法:
int[] avgScore1 = new int[5] {1,2, 3, 4, 5};//下标和元素个数要一样,不然会报错
int[] avgScore2= new int[] {1, 2, 3, 4,5};//可不写下标(元素的索引),系统会自己查元素数量
int[] avgScore3 = {1,2,3,4,5,6};//这个最简单,但上面的在特殊时候也能用得到

for循环实现数组的遍历

 #region 2 for循环实现数组的遍历
 static void Test2()
 {
     //数组遍历用for循环来实现,遍历:就是循环把数组中所有元素取出来
     int[] scoreArray = { 6, 8, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14 };//最简单写法
     int addArray = 0;
     for(int i=0;i<scoreArray.Length;i++)//这里的.Length属性是获取数组元素总个数从1开始数
     {
         addArray += scoreArray[i];
     }
     addArray /= (scoreArray.Length );
     Console.WriteLine(addArray );
 }
 #endregion

小结:这里的.Length属性是获取数组元素总个数从1开始数

foreach循环实现数组的遍历

#region 3 foreach循环实现数组的遍历
 static void Test3()
 {
     int[] scoreArrey = { 5, 6, 7, 8,9 };
     int addArrey = 0;
     foreach (int add in scoreArrey )
     {
         addArrey += add;
     }
     addArrey /= scoreArrey.Length;//数组元素总数除以数组元素总个数==平均数
     Console.WriteLine(addArrey);
 }
 #endregion

小结:foreach (int add in scoreArrey )数组遍历专用,循环依次把参数二的数组的元素赋值给第一个参数。不用再给数组元素个数单独++。很方便

字符串分割与拼接、替换

 #region 4 字符串分割与拼接、替换
 static void Test4()
 {
     string data1 = "AB CD EF 00";//空格隔开的字符串
     string[] stringArray = data1.Split();//不填就默认是空格分隔,因为上面字符串特征是空格
     string data2 = string.Join(",",stringArray);//组合字符串,并在数组元素之间用 , 隔开
     Console.WriteLine(data2);
     Console.WriteLine(stringArray[1]);//分隔后可以单独拿出数组元素来用

     //使用逗号分隔,然后用&重组合
     string data3 = "AB,CD,EF,66";
     string[] stringArray1 = data3.Split(',');//以 , 为分隔标记 分成多个元素存为数组
     string data4 = string.Join("&",stringArray1);//元素组合为一个字符串,元素间用&隔开
     Console.WriteLine(data4+"  "+stringArray1.Length);//输出data内容,分割后stringArray1数组个数

     //字符串替换
     string data5 = data3.Replace(',', '=');// 字符串里的 ,全都替换为= 
         Console.WriteLine(data5);
 }
 #endregion

小结:
分隔字符串:分隔前这个字符串要有明显的分隔特征,比如有 空格 ,_ 等符号 ,变量名.Split();会根据()内的符号作为分割标记,分成多个字符串,可以赋值到字符串类型数组内
组合字符串:string.Join(“分隔标记符号”,字符串变量数组名);把一个多个字符串元素的数组的所有元素合并到一起,之间加入想要的标记符号,可以赋值到字符串变量内

值类型和引用类型变量传递

#region 5 值类型和引用类型变量传递
 static void Test5()
 {
    //值类型:int、float、double、枚举......等
    //总结:基本数据类型传递的是变量的“副本”而不是变量的本身,重新开辟新的内存空间来存储,变量修改后相互没影响
     
     
     //引用类型变量又称《对象类型变量》:1字符串、数组、系统库中的各种类、自定义的类
    //总结:引用类型是传递自己地址(指针)地址存的内容是共用的

 }
 #endregion

小结:
值类型:int、float、double、枚举…等
特点:基本数据类型传递的是变量的“副本”而不是变量的本身,重新开辟新的内存空间来存储,另一个变量修改后和最开始的变量相互没影响

引用类型变量:又称《对象类型变量》,1字符串、数组、系统库中的各种类、自定义的类
特点:引用类型是传递自己地址(指针)地址存的内容是共用的

认识大写String和小写string

 #region 6 认识大写String和小写string
 static void Test6()
 {
    //string 是C#编程语言关键字,在C#的IDE中会变蓝色(推荐用它); 是String的别名,是一种数据类型(本质是引用类型)
    //String 是.NET Framework的类
    //使用string时编译器会把它编译成String
    //
 }
 #endregion

小结:方便面能吃但没啥味(String)。加了雕花的牛肉就是牛肉面能吃又好看(string)

6、枚举

常量枚举

 #region 1 常量枚举
  static void Test1()
  {
      //常量特点:常量初始化后,此常量不可再被更改数值
      //常量定义要求:1定义必须同时初始化。2名称要全部大写、有意义
      const double PAL = 3.14;//1定义必须同时初始化。2名称要全部大写、有意义
      double result = PAL * 5 * 5;
      Console.WriteLine($"{result}");
  }
  #endregion

小结:
常量特点:常量初始化后,此常量不可再被更改数值
常量定义要求:1定义必须同时初始化。2名称要全部大写、有意义

枚举的使用

 #region 2枚举的使用
  static void Test2()
  {
      //枚举作用:可以用来定义“有限个变量值”方便选择使用,避免出错。不可被更改
      //枚举特点:可以表示一组描述性的名称,还可以有对应的“整数型”
      //枚举enum不能定义到类的里面

      //自挤定义的枚举
      Gender gender = Gender.Male;
      Console.WriteLine(gender);//输出为Male
      Console.WriteLine((int)gender);//强制转换int类型就输出变为代表Male的整数1

      StoreArea modbus = StoreArea.输入线圈1x;
      Console.WriteLine(modbus);//输出 输入线圈1x
      Console.WriteLine((int)modbus);//输出 自动默认定义的 输入线圈1x 代表数字1

      StoreArea data1 = StoreArea.保持寄存器4x;
      Console.WriteLine((int)data1);
      Console.WriteLine(data1);


      //系统定义的枚举
      DayOfWeek week = DayOfWeek.Monday;//DayOfWeek为系统定义好的枚举,是星期一到星期日,以后还会碰到很多系统定义好的
      switch (week)
      {

          case DayOfWeek.Sunday:

              Console.WriteLine("今天,就i是今天");
              break;
          case DayOfWeek.Monday:

              Console.WriteLine("今天,就i是今天");
              break;
      }
  }
    
  
  public enum Gender//枚举可以用来定义数字,定义性别
  {
      Male = 1,
      Female=0
  }
  public enum DataFormat//枚举可以用来规定格式
  {
      ABCD,
      BADC,
      CDAB,
      DCBA
  }
  public enum StoreArea//枚举可以用来规定格式
  {
      输出线圈0x,
      输入线圈1x,
      输入寄存器3x,
      保持寄存器4x
  }


  //调试很重要,有的调试窗口被关闭了,必须在调试运行时候  主菜单  调试 窗口 里面才会显示出来,非调试运行状态是看不见的
  //要熟练运用调试常用快捷键 F11、F10、F5等等的功能
  #endregion 

小结:枚举内成员是常量

你可能感兴趣的:(C#上位机,c#,visual,studio,windows,笔记,学习)