user3182683
user3182683

Reputation: 101

How can I check if string value exists in array of chars?

#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;
}

I wanna check if the string "cab" for example exists in array of chars like in my case, it should exist, no matter of position in the element in the array of chars.

Upvotes: 1

Views: 1495

Answers (2)

user3125280
user3125280

Reputation: 2829

Not my code:

#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() );
}

Upvotes: 1

npinti
npinti

Reputation: 52185

Assuming that your sub string will not have duplicates, you could use an unordered_set. So you essentially iterate over your s[] and for each character, you will check if the set contains that particular character.

The unordered_set allows O(1) searching, so your algorithm should run in O(n) (n = size of s).

When you find a character in the set which is also within the array, you remove it and continue traversing the array. If by the time your are done traversing the array the set is empty, then you know that your array contains that substring. You can also check to see that the set is not empty each time you remove a character from it, this should reduce execution time.

Upvotes: 1

Related Questions