实习第一天,做了个小练习:
从“agasdasssdasdawqe”中统计所有字母出现次数
想了想用集合来完成,代码如下
namespace Str_stat1
{
class Program
{
static int List_contains(ArrayList arrayList, string str2)
{//这个方法用来检索以char_arr为元素的某个集合中,属性值为str2字符串的值,在集合里的序号
int a = -1;
foreach (char_arr arr in arrayList)
{
if (arr.Letter == str2)
//返回这个arr的序号
{ a= arrayList.IndexOf(arr);
}
}
return a;
}
static void Main(string[] args)
{
String str = "agasdasssdasdawqe";
String str2 = "";
int num = str.Length;
ArrayList list1 = new ArrayList();
for (int i = 0; i < num; i++)
{
//对字符串的字母一一取出
str2 = str.Substring(0,1);
str = str.Remove(0, 1);
//Console.WriteLine(str2);
char_arr arr = new char_arr();
int n = List_contains(list1, str2);
//当集合里存在有这个属性的元素
if (n!=-1)
{
arr = (char_arr)list1[n];
list1.RemoveAt(n);
arr.Number++;
list1.Add(arr);
}
//某字母第一次出现
else
{
arr.Letter = str2;
arr.Number++;
list1.Add(arr);
}
}
foreach (char_arr arr2 in list1)
{//输出结果
Console.WriteLine(arr2.Letter+":"+arr2.Number);
}
Console.ReadLine();
}
}
class char_arr
{//这个类用来记录数据:什么字母;有几个字母
string letter=null;
int number=0;
//设置属性
public string Letter { get => letter; set => letter = value; }
public int Number { get => number; set => number = value; }
}
}