2天前笔试题尽力写了。。。。
namespace ElementPrintf
{
class Program
{
static void Main(string[] args)
{
GetElementNum("CaCO3");
Console.WriteLine();
GetElementNum("Fe2(SO4)3");
Console.WriteLine();
GetElementNum("Cu2(SO4)4SO2Na(OH)2");
}
static void GetElementNum(string str)
{
List<String> elementList = new List<string>();//元素名列表
List<int> numList = new List<int>();//对应个数列表
string tempstr = "";//临时元素名
int index_e = -1;
for (int i = 0; i < str.Length; i++)//遍历判断
{
if (str[i]>='A'&& str[i] <= 'Z')//大写确定新元素
{
index_e++;
tempstr=str[i].ToString();
i++;
while (i < str.Length-1 && (str[i] >= 'a' && str[i] <= 'z'))//小写元素拼接元素名
{
tempstr+=str[i].ToString();
i++;
}
i--;
if (i < str.Length - 1 && (str[i + 1] >= '0' && str[i + 1] <= '9'))//判断下一字符是否为数字
{
i++;
SetElement(elementList, numList, tempstr, int.Parse(str[i].ToString()));//调用添加元素数目列表
}
else//不在括号内且后面非数字默认个数为1
{
SetElement(elementList, numList, tempstr,1);
}
}
else if (str[i] == '(' )//判断是否为(
{
i++;
int temp = i;//保存i
while (str[i]!=')')
{
i++;
}
i++;
int num = int.Parse(str[i].ToString());//括号外数字
i = temp;
while (str[i] != ')')//退出
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
index_e++;
tempstr = str[i].ToString();
i++;
while (str[i] >= 'a' && str[i] <= 'z')
{
tempstr += str[i].ToString();
i++;
}
i--;
if ((str[i + 1] >= '0' && str[i + 1] <= '9'))
{
i++;
SetElement(elementList, numList, tempstr, num * int.Parse(str[i].ToString()));
}
else
{
SetElement(elementList, numList, tempstr, num);
}
}
if (i>str.Length-1)//避免错误元素无)死循环
{
Console.Write("请输入正确元素");
break;
}
i++;
}
i++;
}
else
{
Console.Write("请输入正确元素");
}
}
for (int i = 0; i < elementList.Count; i++)//遍历输出
{
Console.Write(elementList[i]+numList[i]);
}
}
static void SetElement(List<string> s,List<int> n,string str,int count)
{
for (int i = 0; i < s.Count; i++)//遍历判断是否已存在该元素
{
if (s[i]==str)//存在,原基础增加
{
if (count > 0)
{
n[i] += count;
}
return;
}
}
//不存在添加到元素列表
s.Add(str);
n.Add(count);
}
}
}