Search code examples
c++googlemock

Comparing the contents of strings regardless of its order


Is there a way to compare two strings' contents not taking into account their order? i.e edcc and cdce are true since the frequency of each letter and the letter itself match

For instance, the following should be true.

std::string s1 = "Hello World";
std::string s2 = "World Hello";

The following seems equivalent to EXPECT_EQ(s1, s2) but is there any way to verify just the contents?

EXPECT_THAT(s1, ContainerEq(s2));

The following won't work as it seems to only work with containers like vector, arrays...

EXPECT_THAT(s1, UnorderedElementsAre(s2));

I have also tried the following void attempt

std::vector<char> vec1(s1.begin(), s1.end());
std::vector<char> vec2(s2.begin(), s2.end());

EXPECT_THAT(vec1, UnorderedElementsAreArray(vec2));

Solution

  • There's no need to copy things into std::vector, std::string is also an accepted container to UnorderedElementsAreArray:

    EXPECT_THAT(s1, ::testing::UnorderedElementsAreArray(s2));
    

    https://godbolt.org/z/E9zKs4fxx

    Getting it to ignore case would be a bit more involved, as it would require some custom matcher probably (ready matcher ignoring case only matches whole string).