How to check if two strings have the same words in different order with C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>

std::vector<std::string> extract_string_words_into_a_vector(const std::string str2, std::vector<std::string> wordsOfStr2) {
    std::istringstream iss(str2);

    std::vector<std::string> words(std::istream_iterator<std::string>(iss), {});

    return words;
}

bool two_strings_have_same_words_in_different_order(const std::string str1, const std::string str2) {
    std::vector<std::string> wordsOfStr1, wordsOfStr2;
    
    wordsOfStr1 = extract_string_words_into_a_vector(str1, wordsOfStr1);
    wordsOfStr2 = extract_string_words_into_a_vector(str2, wordsOfStr2);

    for (const std::string &str1word : wordsOfStr1) {
        if (std::find(wordsOfStr2.begin(), wordsOfStr2.end(), str1word) == wordsOfStr2.end())  {
            return false;
        }
    }

    return true;
}

int main()
{
    std::string str1 = "java c# c c++ python";
    std::string str2 = "python c++ java c# c";

    if (two_strings_have_same_words_in_different_order(str1, str2)) {
        std::cout << "yes" << std::endl;
    }
    else {
        std::cout << "no" << std::endl;
    }
}

 
 
 
/*
run:
 
yes
 
*/

 



answered May 9, 2024 by avibootz
...