2014-01-13 107 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()); 
} 
相關問題