刚做了华为笔试题,有个ini文件解析的题,写了三遍终于过了,记录一下经验和收获。
题意:
INI文件由节、键、值组成。
节
[section]
参数
(键=值)
name=value
注解
注解使用分号表示(;)。在分号后面的文字,直到该行结尾都全部为注解。
; comment textINI文件的数据格式的例子(配置文件的内容) [Section1 Name]
KeyName1=value1
KeyName2=value2
...
[Section2 Name]
KeyName21=value21
KeyName22=value22
其中:
[Section1 Name]用来表示一个段落。
这是百度百科对ini文件的定义,题目要求就是对这个文件解析成为{section}{key}{value}这样的格式打印出来,先按照section排序, 再按照key排序,排序标准是字典序。
题解:这个题目不难,就是坑点有点多,下面有列举。思路就是用一个结构体存一条记录的信息,然后重载小于号就可以实现排序。解析的过程是将整行读入,然后在进行处理,一开始是用一个字符一个字符读入的处理的,但是只过了50%,后来干脆暴力一点把可能有坑的地方都考虑上,就一遍过了。
坑点:
1. 存在注释用‘;’表示分号之后的整行都是注释要忽略掉,这个分号可能出现在某行首位,也能出现在行中,但是不会出现在某个名称之间和key,value对之间(还算讲理了)
2. 空格问题,到处都存在空格(行首,行末,行中,等号两侧,名称中间也有可能),名称内部的空格要留下,首位的空格要去掉(这就是为什么换成整行读和处理的原因了),所以每次拿到一行对首尾去掉空格,然后解析完之后再对行首尾去空格,基本就没问题了。
3.存在空行,可能存在一个整行都是空的
大概就是以上几点了。
代码:
#include<iostream>
#include<fstream>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<stdio.h>
#include<utility>
#include<algorithm>
#include<map>
#include<stack>
#include<set>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1e4+5;
const int mod = 1e9+7;
const int INF = 1<<30;
struct node
{
string section, key, value;
node(string s="", string k="", string v="")
{
section = s;
key = k;
value = v;
}
bool operator<(const node& n) const
{
if(section != n.section)
return section<n.section;
return key<n.key;
}
}in[maxn];
void trim(string& s)
{
s.erase(s.find_last_not_of(" ") + 1);
s.erase(0, s.find_first_not_of(" "));
}
int main( )
{
//freopen("input.txt", "r", stdin);
char ch;
string preSection, line;
int num = 0, len;
while(getline(cin, line))
{
trim(line);
if(line == "" || line[0]==';')
continue;
ch = line[0];
len = line.length();
if(ch=='[')
{
preSection = "";
for(int i=1; i<len-1; i++)
{
if(line[i] == ';' || line[i]==']')
break;
preSection += line[i];
}
trim(preSection);
preSection = "{" + preSection + "}";
}
else
{
string curKey = "", curValue = "";
int i;
for(i=0; i<len; i++)
{
if(line[i] == '=')
break;
curKey += line[i];
}
i++;
for(; i<len; i++)
{
if(line[i] == ';')
break;
curValue += line[i];
}
trim(curKey);
curKey = "{" + curKey + "}";
trim(curValue);
curValue = "{" + curValue + "}";
in[num++] = node(preSection, curKey, curValue);
}
}
sort(in, in+num);
for(int i=0; i<num; i++)
cout<<in[i].section<<in[i].key<<in[i].value<<endl;
return 0;
}