题目来自<系统程序员成长计划>
作者:李先静.
状态变化如下
#include <string>
#include <iostream>
using namespace std;string s = "[GRP]\n\
name = def \n\
data = 2016.11.29 \r\n\
; this is a comment \r\n\
str = this is a test \n\
[zhangshan] \n\
;\n\
name = pengjun \n\
data = 3355456";enum STATE
{STAT_NONE = 0,STAT_GROUP,STAT_KEY,STAT_VALUE,STAT_COMMENT
};void IniBufferParse(const string& s)
{STATE state = STAT_NONE;size_t groupStart = 0, groupEnd = 0;size_t commentStart = 0, commentEnd = 0;size_t keyStart = 0, keyEnd = 0;for (size_t i = 0; i < s.size(); i++){switch (state){case STAT_NONE:if (s[i] == '['){ state = STAT_GROUP;groupStart = i+1;}else if (s[i] == '\r' || s[i] == '\n'){state = STAT_NONE;}else if (s[i] == ';'){state = STAT_COMMENT;commentStart = i + 1;}else if (!isspace( s[i]) ){state = STAT_KEY;keyStart = i;}break;case STAT_GROUP:if (s[i] == ']'){ state = STAT_NONE;groupEnd = i;cout << "group = " << s.substr(groupStart, groupEnd - groupStart) << endl;}else if (s[i] == '\r' || s[i] == '\n'){state = STAT_NONE;}break;case STAT_COMMENT:if (s[i] == '\r' || s[i] == '\n'){state = STAT_NONE;commentEnd = i;cout << "comment = " << s.substr(commentStart, commentEnd - commentStart) << endl;break;}break;case STAT_KEY:if (s[i] == '\r' || s[i] == '\n'){state = STAT_NONE;keyEnd = i;string kvString = s.substr(keyStart, keyEnd - keyStart);size_t i = kvString.find_first_of('=');if (i == string::npos)break;cout << "key = " << kvString.substr(0,i-1) << ". value = " << kvString.substr(i+1) << endl;break;}break;default:break;}}}int main()
{IniBufferParse(s);return 0;
}
运行结果
group = GRP
key = name. value = def
key = data. value = 2016.11.29
comment = this is a comment
key = str. value = this is a test
group = zhangshan
comment =
key = name. value = pengjun
请按任意键继续. . .