序
开发一款windows端上位机,需要对文本中的数据进行读写,使用该方法可提取字符串中的数字及指定字符。
txt文本内容格式:
数据1(bit):12290,3
数据2(bit):12291,128
代码段:
string Init_txt_text = System.IO.File.ReadAllText(Application.StartupPath + "\\Save_data.txt"); //读取相对路径的文本
for (i = 0; i < Init_txt_text.Length; i++)
{
char ch = Init_txt_text[i];
if (((ch == '(') || strflag) && (ch != ':')) //每行ID结束后‘:’后跟着地址‘,’后跟着位数
{
if (ch == ')')
{
if (temp == "bit")
canonical_table_Init[Line_flag, 0] = 0;
else
canonical_table_Init[Line_flag, 0] = 1;
temp = "";
}else if (ch == ',')
{
canonical_table_Init[Line_flag, 1] = int.Parse(temp); //地址
temp = "";
}else if (ch == '\n') //出现‘\n’代表每段结束
{
canonical_table_Init[Line_flag, 2] = int.Parse(temp); //位数
temp = "";
Line_flag++;
strflag = false;
}else if(strflag){
if (ch >= '0' & ch <= '9')
{
temp += ch.ToString();
}
else
{
temp += ch;
}
}
if(ch != '\n')
strflag = true;
}
}