Looking for a proper function

Nov 2, 2019 at 4:56pm
Hi I'm looking for a function similar to std::string::compare() but outputs the position of the first element that doesn't match the string. Does a function like this exist in the standard library? Thanks in advance.
Nov 2, 2019 at 5:13pm
What does it mean, "the first element that doesn't match the string"? An element is a single character? How does an element match a string?

Can you show us an example of what you mean?
Nov 2, 2019 at 6:17pm
Nah, a function like that is too niche to be of widespread use.
Edit: A more accurate answer is "almost". See next post.

original post:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Example program
#include <iostream>
#include <string>
#include <algorithm>

// outputs the position of the first element that doesn't match
int first_not_match(const std::string& a, const std::string& b)
{
    int n = std::min(a.length(), b.length());
    for (int i = 0; i < n; i++)
    {
        if (a[i] != b[i])
            return i;
    }
    return n;
}

int main()
{
    std::cout << first_not_match("", "") << '\n';
    std::cout << first_not_match("1", "") << '\n';
    std::cout << first_not_match("", "1") << '\n';
    std::cout << first_not_match("1", "1") << '\n';
    std::cout << first_not_match("cat", "cab") << '\n';
    std::cout << first_not_match("call", "caller") << '\n';
}


Maybe there's a function in <algorithm> that could be used as a building block, but the STL is heavily iterator-based so you'd convert the iterator to an index.

EDIT: I believe std::mismatch will do what you want.
http://www.cplusplus.com/reference/algorithm/mismatch/

https://stackoverflow.com/a/21288219/8690169
Last edited on Nov 2, 2019 at 6:44pm
Nov 2, 2019 at 6:34pm
In hindsight, of course there's an algorithm for it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <algorithm>

int find_mismatch_index(const std::string& a, const std::string& b)
{
     return std::mismatch(a.begin(), a.end(), b.begin(), b.end()).first - a.begin();
}

int main ()
{
    std::cout << find_mismatch_index("", "") << '\n';
    std::cout << find_mismatch_index("1", "") << '\n';
    std::cout << find_mismatch_index("", "1") << '\n';
    std::cout << find_mismatch_index("1", "1") << '\n';
    std::cout << find_mismatch_index("cat", "cab") << '\n';
    std::cout << find_mismatch_index("call", "caller") << '\n';
}

0
0
0
1
2
4
Last edited on Nov 2, 2019 at 6:41pm
Topic archived. No new replies allowed.