数组的遍历和字符串的操作

来源:互联网 发布:南京水科院怎么样知乎 编辑:程序博客网 时间:2024/05/17 08:39

数组的遍历

遍历数组有三种循环方式

  • for循环
int i = 0;int[] scores = { 12, 16, 2, 6, 7, 23, 7, 4, 7 };Console.WriteLine("for循环遍历数组");for(i = 0; i < scores.Length; i++){    Console.WriteLine(scores[i]);}
  • while循环
while (i < scores.Length)            {                Console.WriteLine(scores[i]);                i++;            }
  • foreach循环
foreach (int temp in scores)            {                Console.WriteLine(temp);            }

三种循环方法,只有foreach循环遍历数组时,不能够对数组里的元素进行任何的操作。

字符串的操作

字符串实质上可以看做是一个字符数组,所以字符串也可以遍历并且输出

string str = "  www.baidu.COM  ";for(int i = 0; i < str.Length; i++){    Console.Write(str[i] + " ");}

修改字符串的方法有很多,下面是示例代码

string res1 = str.ToUpper(); //将字符串转换成大写string res2 = str.ToLower(); //将字符串转换成小写string res3 = str.Trim(); //删除字符串前后端的空白string res4 = str.TrimStart(); //删除字符串前面的空白string res5 = str.TrimEnd(); //删除字符串后面的空白string[] res6 = str.Split('.'); //将字符串以指定的字符分开

最后的输出结果如下图
输出结果

阅读全文
0 0
原创粉丝点击