请帮我分析一下 [英] Please help me in parsing

查看:74
本文介绍了请帮我分析一下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询



假设我在文本文件中有以下行

I have an query

Suppose i have the following line in a text file

Hi i am xyxabc and i work for xyz







I want the output to be "and i work for"



我有以下代码


I have the following code

#include <fstream>
#include <string>
#include <iostream>
bool ParseLine(const std::string& line, std::string& key, std::string& value);
 
class Demo
{
public:
    typedef struct _Data 
    {
        std::string abc;
		
        
    } Data;
 
    Data data;
};
 
int main()
{
    std::ifstream ifs("Ca.txt");
    std::string line;
    std::string key;
    std::string value;
    Demo obj;
    while(!ifs.eof())
    {
        std::getline(ifs, line);
        if (ParseLine(line, key, value))
        {
            if (0 == key.compare("student"))
            {
                obj.data.name = value;
            }
         
			 else if (0 == key.compare("abc"))
            {
				obj.data.content = value;
            }
            else
            {
                std::cerr<<"Unknow key:" << key << std::endl;
            }
        }
    }
    return 0;
}
 
bool ParseLine(const std::string& line, std::string& key, std::string& value)
{
    bool flag = false;
    
if (line.find("//") != 0)
    {
        size_t pos = line.find(" ");
        if (pos != std::string::npos)
        {
            key = line.substr(0, pos);
			 size_t pos1 = line.find(";");
            value = line.substr(pos + 1, pos1);
            flag = true;
        }
    }
	
    return flag;
}







我想要输出,我的工作是在xyz之前。




I want the output to be and i work for that is before xyz.

推荐答案

我不会涉及太多,但也许这会让你开始。始终尝试从最简单的问题版本开始。我看到这样的事情:



I won't go into much, but maybe this gets you started. Always try to start from the simplest version of the problem. I see something like this:

#include <string>
using namespace std;

int findSchoolEnd(const string & str) {
   size_t pos = str.find("xyxabc");
   if (pos == string::npos) return -1;
   return pos + string("xyxabc").length();
   }

int findStudentBegin(const string & str) {
   size_t pos = str.find("xyz");
   if (pos == string::npos) return -1;
   return pos;
   }

string getMiddleStuff(const string & str, size_t begin, size_t end) {
   if (begin == string::npos) return "";
   if (end == string::npos) return "";
   return str.substr(end, begin-end);
   }

int main() {
   string str = "Hi i am xyxabc and i work for xyz";
   size_t begin = findSchoolEnd(str);
   size_t end   = findStudentBegin(str);
   string result = getMiddleStuff(str, end, begin);
   }





只有核心工作后才开始进行关键比对,就像之前的代码一样。



祝你好运!



Only begin working on the key comparisons after the core works, like the previous code does.

Good luck!


这篇关于请帮我分析一下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆