zoukankan      html  css  js  c++  java
  • 状态机学习(二)解析INI文件

    题目来自<系统程序员成长计划>  

    作者:李先静.

    状态变化如下

    #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
    请按任意键继续. . .

  • 相关阅读:
    Selenium自动化Chrome浏览器 在windows下窗口最大化
    Linux下的压缩解压缩命令详解及实例
    Windows下及Mac下的IntelliJ IDEA快捷键
    Missing artifact com.oracle:ojdbc6:jar:10.2.0.4.0问题解决 ojdbc包pom.xml出错
    使用cmd命令进行导入
    导入dmp文件时,需要删除原有ORACLE数据库实例
    HTML编码规范、CSS编码规范
    javascript函数与表达式
    JS中闭包、函数与对象的介绍和用法
    JS中typeof和instanceof用法区别
  • 原文地址:https://www.cnblogs.com/itdef/p/6112765.html
Copyright © 2011-2022 走看看