namespace _12.集合的练习01
{
class Program
{
static void Main(string[] args)
{
/*
将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中.
最终将两个集合合并为一个集合,并且奇数显示在左边,偶数显示在右边.
*/
int[] iArray = {1,2,3,4,5,6,7,8,9,10};
List<int> a = new List<int>(); //用来保存偶数
List<int> b = new List<int>(); //用来保存奇数
List<int> ab = new List<int>(); //用来保存a+b集合的
for (int i = 0; i < iArray.Length; i++)
{
if (iArray[i] % 2 == 0)
{
a.Add(iArray[i]);
}
else
{
b.Add(iArray[i]);
}
}
b.AddRange(a);
foreach (var item in b)
{
Console.Write(item);
}
Console.ReadKey();
}
}
}
练习2:提示用户输入一个字符串,通过foreach循环将用户输入的字符串赋值给一个字符数组.
namespace _13.集合的练习02
{
class Program
{
static void Main(string[] args)
{
/*
提示用户输入一个字符串,
通过foreach循环将用户输入的字符串赋值给一个字符数组.
*/
Console.WriteLine("请输入一个字符串:");
string str = Console.ReadLine();
char[] c1 = new char[str.Length];
int i = 0;
foreach (var item in str) //我们可以将str看成是一个只读的字符数组,所以item中装的是字符
{
c1[i] = item;
i++;
}
for (int j = 0; j < c1.Length; j++)
{
Console.Write(c1[j]);
}
Console.ReadKey();
}
}
}
练习3:
统计welcome to china中每一个字符出现的次数,不考虑大小写.(面试题)
namespace _14.集合的练习03
{
class Program
{
static void Main(string[] args)
{
/*
统计welcome to china中每一个字符出现的次数,不考虑大小写.(面试题)
*/
string str = "Welcome to China";
//字符---->出现的次数
//键----->值
Dictionary<char,int> dic= new Dictionary<char, int>();
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
{
continue;
}
//如果dic这个键值对集合中已经包含了当前循环的键,
if (dic.ContainsKey(str[i]))
{
dic[str[i]]++;
}
else //这个字符在集合中是调用此出现
{
dic[str[i]] = 1;
}
}
foreach (KeyValuePair<char,int> item in dic)
{
Console.WriteLine("字母:{0}出现了{1}次.",item.Key,item.Value);
}
Console.ReadKey();
}
}
}