AnilJ
AnilJ

Reputation: 2121

Substring (std::substr) at special characters in C++

have a string as:

access/2/NOTIF/PI/%24cname%3D/bldg/temp/s/2%24

When I try to run following code,

size_t found = str.find_first_of("NOTIF");
if (found != std::string::npos) {
    std::cout << "NOTIF found" << " at pos: " << found << std::endl;
    std::string substr = str.substr(found+8, m_name.length());
    std::cout << "SUBSTR: " << substr << std::endl;
}

I correctly get the position of N, which is 9. However when I try to subsr for '$', which is string is encoding as %24, it fails. Ideally, I am looking to extract a sub string between $ and $ (i.e. between %24 and %24). Substring is somehow is not recognizing this %24 as $.

What could be the problem here? Do I have to preprocess this before I can call substr?

Upvotes: 1

Views: 1586

Answers (1)

Praetorian
Praetorian

Reputation: 109119

Ideally, I am looking to extract a sub string between $ and $ (i.e. between %24 and %24)

Then search for %24, don't bother with passing the string through some API to convert it back to $.

auto first = s.find("%24");               // Look for first %24
auto second = s.find("%24", first + 1);   // Look for second %24
std::cout << s.substr(first + 3, second - (first + 3)); // This is the substring you're looking for

Live demo

Upvotes: 1

Related Questions