2014-01-13 187 views
1
#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”是否存在于字符数组中,就像在我的情况下一样,它应该存在,无论位于字符数组中的元素中。如何检查字符串值是否存在于字符数组中?

+0

或只是'find'?它正是这样 – user3125280

+0

看来你正在寻找['std :: includes'](http://en.cppreference.com/w/cpp/algorithm/includes)。 –

+0

@JoachimPileborg可以说,find方法是字符串类的一部分,因此可能会更快,并且默认情况下忽略空值 – user3125280

回答

1

假设您的子字符串不会有重复项,您可以使用unordered_set。所以你基本上遍历你的s[]和每个角色,你会检查该组是否包含该特定角色。

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

当您在同样位于数组中的集合中找到一个字符时,将其移除并继续遍历该数组。如果在遍历数组的时候这个集合是空的,那么你知道你的数组包含了这个子串。您还可以检查每次从中删除角色时该设置不是空的,这会减少执行时间。

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()); 
} 
相关问题