Net基础篇_学习笔记_第九天_数组_三个练习

时间:2023-03-09 08:46:05
Net基础篇_学习笔记_第九天_数组_三个练习

练习一:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _数组练习01
{
class Program
{
static void Main(string[] args)
{
string str = null;
string[] names = { "老杨","老李","老赵","老孙","老沈"};
for (int i = ; i < names.Length; i++)
{
str += names[i] + "|";
}
Console.WriteLine(str);
Console.ReadKey();
}
}
}

优化为:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _数组练习01
{
class Program
{
static void Main(string[] args)
{
string str = null;
string[] names = { "老杨","老李","老赵","老孙","老沈"};
for (int i = ; i < names.Length-; i++)
{
str += names[i] + "|";
}
Console.WriteLine(str+names[names.Length-]);
Console.ReadKey();
}
}
}

练习二:如遇正数,将这个位置元素的值加1,如遇负数,将这个位置元素的值减1,如遇0,则不变。

int nums={0,5,-8,-41,5,94,-1,-22};

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _数组练习01
{
class Program
{
static void Main(string[] args)
{
int[] nums = { ,,,-,-,-,};
for (int i = ; i < nums.Length; i++)
{
if (nums[i] > )
{
nums[i] += ;
}
else if (nums[i] < )
{
nums[i] -= ;
}
}
for (int i = ; i < nums.Length; i++)
{
Console.WriteLine(nums[i]);
}
Console.ReadKey();
}
}
}

联系三:将一个字符串数组的元素顺序进行反转

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _数组练习01
{
class Program
{
static void Main(string[] args)
{
string[] names = { "a", "b", "c" ,"d"};
for (int i = ; i <names.Length/; i++)
{
//交换两个变量最简单的方式就是声明第三方的一个变量。
string _temp = names[i];
names[i] = names[names.Length - - i];
names[names.Length - - i] = _temp;
}
for (int i = ; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}