如何检查字符数组中是否存在字符串值?

时间:2014-01-13 05:40:18

标签: c++ arrays char

#include <iostream>

using namespace std;

int main()
{
    string str = "cab";
    string d = "";
    char s[] = {'a', 'b', 'c', 'd', 'e'};
    for(int i = 0; i < sizeof(s) / sizeof(s[0]); i++){
        for(int j = 0; j < str.length(); j++){
            if(str[j] == s[i]){
                d += s[i];
            }
        }
    }
    cout << d << endl;
    return 0;
}

我想检查字符串“cab”是否存在于chars数组中,就像我的情况一样,它应该存在,无论字符数组中元素的位置如何。

2 个答案:

答案 0 :(得分:1)

假设您的子字符串没有重复项,您可以使用unordered_set。因此,您基本上遍历s[]并且对于每个字符,您将检查该集合是否包含该特定字符。

unordered_set允许O(1)搜索,因此您的算法应该以O(n)运行(n = s的大小)。

当您在集合中找到同样位于数组中的字符时,将其删除并继续遍历该数组。如果在完成遍历数组时该集合为空,那么您就知道您的数组包含该子字符串。每次从中删除字符时,您还可以检查该集合是否为空,这样可以缩短执行时间。

答案 1 :(得分:1)

不是我的代码:

#include <string>
#include <iostream>
#include <algorithm>

void print(std::string::size_type n, std::string const &s)
{
    if (n == std::string::npos) {
        std::cout << "not found\n";
    } else {
        std::cout << "found: " << s.substr(n) << '\n';
    }
}

int main()
{
    std::string str = "cab";
    std::string::size_type n;
    std::string const s = "This is a string";

    // search from beginning of string
    n = s.find("is");
    print(n, s);

    // search from position 5
    n = s.find("is", 5);
    print(n, s);

    // find a single character
    n = s.find('a');
    print(n, s);

    // find a single character
    n = s.find('q');
    print(n, s);

    //not the best way
    for(char c : s)
     s.find(c); //will be npos if it doesn't exist

    //better
    std::includes( s.begin(), s.end(),
           str.begin(), str.end() );
}