Comparing two strings for characters

Hi,

Im guessing this maybe uses regex or an iterator or something? but just wondering how I would be able to check to see if certain string characters were the same? for example:

std:string myString;
inside myString I have the following output: 12b2c69z77m so the data inside the string is just 1 or 2 numbers followed by a letter. These are all individual data so in the above example its 12b 2c 69z 77m I currently do not uses spaces or brackets to seperate them as I dont know how to use regex (or something similar) to remove the brackets or spaces from a search.

I would like to be able to say in code:

1
2
3
4
if (any of the combinations in myString are the same, such as 12b appearing twice)
{
    callRandomFunct;
}
Last edited on
This can be done quite easily without using the <regex> library.
But learning to use regular expressions is very rewarding in the long run.

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
27
28
#include <iostream>
#include <string>
#include <regex>
#include <set>

bool has_duplicates( std::string str )
{
    static const std::regex re( "[0-9]{1,2}" /* one or two decimal digits */
                                "[^0-9]" /* followed by a character that is not a decimal digit */  ) ;

    std::set<std::string> tokens ;

    // http://en.cppreference.com/w/cpp/regex/regex_token_iterator
    using iterator = std::sregex_token_iterator ;
    for( iterator iter( std::begin(str), std::end(str), re ) ; iter != iterator() ; ++iter )
    {
        // http://en.cppreference.com/w/cpp/container/set/insert
        if( !( tokens.insert( *iter ).second ) ) return true ; // found a duplicate
    }

    return false ; // did not find any duplicates
}

int main()
{
    for( std::string str : { "12b2c69z77m", "12b2c69z12b77m" } )
        std::cout << '"' << str << "\" has duplicates? " << std::boolalpha << has_duplicates(str) << '\n' ;
}

http://coliru.stacked-crooked.com/a/585eda2163f7ce06
Topic archived. No new replies allowed.