1

i got a word that is

AD#Andorra

Got a few questions:

How do i check AD?Andorra exist

? is a wildcard, it could be comma or hex or dollar sign or other value

then after confirm AD?Andorra exist, how do i get the value of ?

Thanks, Chen

0

4 Answers 4

4

The problem can be solved generally with a regular expression match. However, for the specific problem you presented, this would work:

std::string input = getinput();
char at2 = input[2];
input[2] = '#';
if (input == "AD#Andorra") {
    // match, and char of interest is in at2;
} else {
    // doesn't match
}

If the ? is supposed to represent a string also, then you can do something like this:

bool find_inbetween (std::string input,
                     std::string &output,
                     const std::string front = "AD",
                     const std::string back = "Andorra") {
    if ((input.size() < front.size() + back.size())
        || (input.compare(0, front.size(), front) != 0)
        || (input.compare(input.size()-back.size(), back.size(), back) != 0)) {
        return false;
    }
    output = input.substr(front.size(), input.size()-front.size()-back.size());
    return true;
}
1
  • A nightmare to debug! Please, please don't use one-line if & return.
    – gwiazdorrr
    Aug 6, 2012 at 15:56
2

If you are on C++11/use Boost (which I strongly recommend!) use regular expressions. Once you gain some level of understanding all text processing becomes easy-peasy!

#include <regex> // or #include <boost/regex>

//! \return A separating character or 0, if str does not match the pattern
char getSeparator(const char* str)
{
    using namespace std; // change to "boost" if not on C++11
    static const regex re("^AD(.)Andorra$");
    cmatch match;
    if (regex_match(str, match, re))
    {
        return *(match[1].first);
    }
    return 0;
}
0

assuming your character always starts at position 3! use the string functions substr:

your_string.substr(your_string,2,1)
1
  • I wouldn't use substr for checking just one (fixed) position inside a string. Aug 6, 2012 at 11:06
0

If you are using C++11, i recommend you to use regex instead of direct searching in your string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.