检查字符串是否包含C中的字符串

新手上路,请多包涵

我有一个 std::string 类型的变量。我想检查它是否包含某个 std::string 。我该怎么做?

如果找到字符串,是否有一个函数返回true,如果没有,则返回false?

原文由 neuromancer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 939
2 个回答

使用 std::string::find 如下:

 if (s1.find(s2) != std::string::npos) {
    std::cout << "found!" << '\n';
}

注:“找到了!” will be printed if s2 is a substring of s1 , both s1 and s2 are of type std::string .

原文由 Matthieu N. 发布,翻译遵循 CC BY-SA 4.0 许可协议

注意:我知道这个问题需要一个函数,这意味着用户正在尝试找到更简单的东西。但我仍然发布它以防有人发现它有用。

使用后缀自动机的方法。它接受一个字符串(haystack),然后您可以输入数十万个查询(needles)并且响应将非常快,即使 haystack 和/或 needle 是非常长的字符串。

阅读此处使用的数据结构: https ://en.wikipedia.org/wiki/Suffix_automaton

 #include <bits/stdc++.h>

using namespace std;

struct State {
  int len, link;
  map<char, int> next;
};

struct SuffixAutomaton {
  vector<State> st;
  int sz = 1, last = 0;

  SuffixAutomaton(string& s) {
    st.assign(s.size() * 2, State());
    st[0].len = 0;
    st[0].link = -1;
    for (char c : s) extend(c);
  }

  void extend(char c) {
    int cur = sz++, p = last;
    st[cur].len = st[last].len + 1;
    while (p != -1 && !st[p].next.count(c)) st[p].next[c] = cur, p = st[p].link;
    if (p == -1)
      st[cur].link = 0;
    else {
      int q = st[p].next[c];
      if (st[p].len + 1 == st[q].len)
        st[cur].link = q;
      else {
        int clone = sz++;
        st[clone].len = st[p].len + 1;
        st[clone].next = st[q].next;
        st[clone].link = st[q].link;
        while (p != -1 && st[p].next[c] == q) st[p].next[c] = clone, p = st[p].link;

        st[q].link = st[cur].link = clone;
      }
    }
    last = cur;
  }
};

bool is_substring(SuffixAutomaton& sa, string& query) {
  int curr = 0;

  for (char c : query)
    if (sa.st[curr].next.count(c))
      curr = sa.st[curr].next[c];
    else
      return false;

  return true;
}

// How to use:
// Execute the code
// Type the first string so the program reads it. This will be the string
// to search substrings on.
// After that, type a substring. When pressing enter you'll get the message showing the
// result. Continue typing substrings.
int main() {
  string S;
  cin >> S;

  SuffixAutomaton sa(S);

  string query;
  while (cin >> query) {
    cout << "is substring? -> " << is_substring(sa, query) << endl;
  }
}

原文由 Chris Vilches 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题