【问题标题】:how to check a string for specific conditions in C++如何在 C++ 中检查字符串的特定条件
【发布时间】:2021-08-20 04:21:15
【问题描述】:

以下 sn-p 显示了我当前输出的一小部分:

1464:       ebfffe4d        bl      da0 <memcpy@plt>
14bc:       ebfffe37        bl      da0 <memcpy@plt>

输出中的每一行都指向一个字符串。我想要归档的是,在这个 只有 memcpy@plt 将打印一次。当字符串包含“bl”时,名称 <...> 内应该打印并且只打印一次,因为 <...> 内的名称是相同的 在这两种情况下。有没有办法得到这个? 我当前的代码如下所示:

class CallFunction {
    private:
        vector<string> content;
    public:
        CallFunction(vector<string> content) {
            this->content = content;
        }
        void print() {
            for(string line: content) {
                if(line.find("bl") != std::string::npos
                && line.find("<") != std::string::npos) {
                    cout << line << endl;
                }
            }
        }
};

int main() {
    string fileName = "libndkmod.s";
    vector<string> content = readFile(fileName);
    CallFunction cf = CallFunction(content);
    cf.print();
}

在此先感谢您的问候!

【问题讨论】:

  • 您可以将名称存储在集合中,并且仅当名称不在集合中时才打印该行。
  • 或者将它们存储在一组中,然后打印整组。
  • 一个名字的多次出现是否会出现在连续的行中?那么你不需要一个集合,只需要一个电流条纹名称的变量。

标签: c++ string substring


【解决方案1】:

我们可以使用unordered_set对子字符串进行去重,如果已经打印了相同的子字符串,则跳过它。

这一步可以提取成一个单一的方法来跟single responsibility principle,这比处理print函数中的重复更自然,这个工作就交给你了。

我们使用unordered_set 而不是std::set,因为unordered_set 搜索起来会更快。

我已将 for 循环从 for(string line: content) 更改为 for(const string&amp; line: content),然后我们避免复制原始字符串,以提高性能。基本上,我们更愿意将for(const auto&amp; item:...) 用于除基本类型之外的对象以避免复制。

我们存储了c++17中引入的string_view以避免复制子字符串,它会节省内存,因为我们避免了不必要的复制。


#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;

class CallFunction {
 private:
  vector<string> content;

 public:
  CallFunction(vector<string> content) { this->content = content; }
  void print() {
    std::unordered_set<std::string_view> mem;
    for (const string& line : content) {
      auto left_pos = line.find("bl");
      auto right_pos = line.find(">");
      if (left_pos != std::string::npos && right_pos != std::string::npos) {
        std::string_view sub_view = {&line.front() + left_pos,
                                     right_pos - left_pos + 1};
        if (mem.count(sub_view)) continue;
        mem.insert(sub_view);
        cout << line << endl;
      }
    }
  }
};

int main() {
  string fileName = "libndkmod.s";
  vector<string> content = {
      "1464:       ebfffe4d        bl      da0 <memcpy@plt>",
      "14bc:       ebfffe37        bl      da0 <memcpy@plt>",
      "14bc:       ebfffe37        bl      da0 <memcmp@plt>"};
  CallFunction cf = CallFunction(content);
  cf.print();
}

Online demo

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2016-05-11
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多