[英]Split string and get values before different delimiters
Given the code:鉴于代码:
procedure example {
x=3;
y = z +c ;
while p {
b = a+c ;
}
}
I would like to split the code by using the delimiters {
, ;
我想通过使用分隔符{
, ;
, and }
. , 和}
。 After splitting, I would like to get the information before it together with the delimiter.拆分后,我想与分隔符一起获取它之前的信息。
So for example, I would like to get procedure example {
, x=3;
例如,我想得到procedure example {
, x=3;
, y=z+c;
, y=z+c;
, }
. , }
。 Then I would like to push it into a list<pair<int, string>> sList
.然后我想将它推入一个list<pair<int, string>> sList
。 Could someone explain how this can be done in c++?有人可以解释一下如何在 C++ 中做到这一点吗?
I tried following this example: Parse (split) a string in C++ using string delimiter (standard C++) , but I could only get one token.我尝试按照这个例子: Parse (split) a string in C++ using string delimiter (standard C++) ,但我只能得到一个标记。 I want the entire line.我想要整条线。 I am new to c++, and the list, splitting, etc. is confusing.我是 C++ 新手,列表、拆分等令人困惑。
Edit: So I have implemented it, and this is the code:编辑:所以我已经实现了它,这是代码:
size_t openCurlyBracket = lines.find("{");
size_t closeCurlyBracket = lines.find("}");
size_t semiColon = lines.find(";");
if (semiColon != string::npos) {
cout << lines.substr(0, semiColon + 1) + "\n";
}
However, it seems that it can't separate based on semicolon separately, openBracket and closeBracket.但是,似乎不能分别基于分号、openBracket 和closeBracket 进行分隔。 Anyone knows how to separate based on these characters individually?有谁知道如何根据这些字符单独分开?
2nd Edit: I have done this (codes below).第二次编辑:我已经这样做了(下面的代码)。 It is separating correctly, I have one for open curly bracket.它正确分离,我有一个用于开大括号。 I was planning on adding the value to the list in the commented area below.我正计划将该值添加到下面评论区域的列表中。 However, when i think about it, if i do that, then the order of information in the list will be messed up.然而,当我想到它时,如果我这样做,那么列表中的信息顺序就会混乱。 As i have another while loop which separates based on open curly bracket.因为我有另一个 while 循环,它基于开大括号分开。 Any idea on how i can add the information in an order?关于如何在订单中添加信息的任何想法?
Example:
1. procedure example {
2. x=3;
3. y = z+c
4. while p{
and so on.等等。
while (semiColon != string::npos) {
semiColon++;
//add list here
semiColon = lines.find(';',semiColon);
}
I think that you should read aboutstd::string::find_first_of function .我认为你应该阅读std::string::find_first_of function 。
Searches the string for the first character that matches any of the characters specified in its arguments.
I have a problem to understand what you really want to achieve.我无法理解您真正想要实现的目标。 Let's say this is an example of the find_first_of
function use.假设这是使用find_first_of
函数的一个示例。
list<string> split(string lines)
{
list<string> result;
size_t position = 0;
while((position = lines.find_first_of("{};\n")) != string::npos)
{
if(lines[position] != '\n')
{
result.push_back(lines.substr(0, position+1));
}
lines = lines.substr(position+1);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.