Итерировать по строке элементов в одну строку - PullRequest
0 голосов
/ 10 апреля 2020

У меня есть две строки, то есть: APPLE и APPLEA. Я хочу перебрать APPLE и проверить, принадлежат ли его символы APPLEA. Я сделал это:

int counter=0;
for (j=0;j<dictionary[i].size();j++)
{
    if (word_to_match.find(dictionary[i][j]) != std::string::npos)
    {
        counter++;
    }
}

Где словарь это просто std :: vector, который имеет APPLE и другие слова. Можно ли избежать for l oop с помощью std :: transform или другого инструмента?

----------------------- ----------- EDIT ------------------------------------

У меня есть это, я не знаю, могло ли это быть даже чище

    std::for_each(dictionary[i].begin(),dictionary[i].end(),[&word_to_match,&counter](char const &c){
        if (word_to_match.find(c) != std::string::npos)
        {
            counter++;
        }
    });

Ответы [ 2 ]

0 голосов
/ 10 апреля 2020

Если заказ не имеет значения, вы можете использовать std::string::find_first_not_of, как указано ниже

int main(){
    std::string str1{"APPLEA"};
    std::string str2{"APPLE"};
    std::string str3{"ApPPLE"};

    std::cout<< (str2.find_first_not_of(str1) == std::string::npos ? "all of str2 belong to str1" : "not all of str2 belong to str1") ;
    std::cout<< (str3.find_first_not_of(str1) == std::string::npos ? "\nall of str3 belong to str1" : "\nnot all of str3 belong to str1") ;
}

Если заказ имеет значение, вы можете использовать std::mismatch, как указано ниже

int main(){
    std::string str1{"APPLE"};
    std::string str2{"APPLEA"};

    auto pair = std::mismatch(str1.begin(), str1.end(), str2.begin());
    pair.first == str1.end() ? std::cout <<"The first string is contained in the second" : std::cout
            << "The first mismatched char in the first string is " <<*pair.first;
    pair.second == str2.end() ? std::cout <<"\nThe second string is contained in the first" : std::cout <<*pair.first
            << "\nThe first mismatched char in the second string is " <<*pair.second;


}
0 голосов
/ 10 апреля 2020

Как насчет std :: count_if

int count = std::count_if(dictionary.begin(), dictionary.end(), [&](const std::string& s){
        return word_to_match.find(s) != std::string::npos;
    });

при условии, что dictionary является контейнером для std::string, например. std::vector<std::string>. Вы можете изменить его соответствующим образом, чтобы соответствовать вашему случаю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...