简体   繁体   English

使用C ++功能解析字符串的最有效方法

[英]most efficient way to parse a string using c++ features

this might be a stupid question (I hope not) but it caught my mind and I'm trying to figure it out. 这可能是一个愚蠢的问题(我希望不是),但是这引起了我的注意,我正在尝试解决。 What is the most efficient way to parse a string using c++ features? 使用C ++功能解析字符串的最有效方法是什么? I appreciate everyone's comments as I, am I'm sure everyone else is too, to become a better programmer! 我很感谢大家的评论,我敢肯定其他人也都愿意成为一个更好的程序员! Here is how I would do it right now with my current knowledge: 现在,以我目前的知识,这就是我现在要做的事情:

#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
void parseLine(string &line)
{
    constexpr char DELIMITER_ONE = '|';
    constexpr char DELIMITER_TWO = '[';
    for (int i = 0; i < line.length(); i++)
    {
        if (line[i] == DELIMITER_ONE || line[i] == DELIMITER_TWO)
        {
            line.erase(i, 1);
        }
    }
    cout << line << endl;
}
int main()
{
    std::string testString = "H|el[l|o|";
    parseLine(testString);

    system("pause");
    return 0;
}
line.erase(
    std::remove_if(line.begin(), line.end(),
        [](char c) { return c == DELIMITER_ONE || c == DELIMITER_TWO; }
    ),
    line.end()
);

See also: erase-remove idiom 另请参阅: 删除删除惯用语

One more way is to use the boost regex library. 另一种方法是使用boost regex库。 Check the below code: 检查以下代码:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main(){
  std::string testString = "H|el[l|o|";
  boost::regex rx("\\||\\[");
  std::string replace = "";
  std::string out = boost::regex_replace(testString, rx, replace);
  std::cout << out << std::endl;
}

C++14 now includes regular expressions standard: C ++ 14现在包括正则表达式标准:

#include <iostream>
#include <string>
#include <regex>

std::string parseLine(const std::string& line);

int main() {
    std::string testString = "H|el[l|o|";
    std::string result = parseLine(testString);
    std::cout << result << std::endl;
    system("pause");
    return 0;
}

std::string parseLine(const std::string& line) {

    std::string input_string;
    std::string result;

    std::smatch sm;
    std::regex r("([a-zA-Z]+)");

    for(input_string = line; std::regex_search(input_string, sm, r); input_string = sm.suffix()) {
        result.append(sm[0].str());
    }
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM