Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compare strings up to "%" char

I would like to implement a string comparison in C++ comparing strings up to a "%" sign.

I could do it like this:

std::equal(str1.begin(), 
           std::find(str1.begin(), str1.end(), L'%'),
           str2.begin());

Since I'm doing this in a loop over many strings, I wonder if there is a method without two distinct string traversals for find and equal (maybe with a predicate that can abort the comparison at any point). Boost is ok.

like image 656
Felix Dombek Avatar asked Dec 05 '14 18:12

Felix Dombek


People also ask

How do I compare strings to characters?

String comparison by Using String Library Functionstrcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative. The strcmp() function compares both strings characters.

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can you use == when comparing strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

Can you use comparison operators with strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


2 Answers

You can try std::mismatch.
The following code will run with C++14 (it requires the template overload with two iterator pairs), but it works quite similar in C++11 (or 03, without lambdas though):

auto iters = std::mismatch( str1.begin(), str1.end(), str2.begin(), str2.end(), 
                     [] (char lhs, char rhs) {return lhs != '%' && lhs == rhs;});


if (iters.first  == str1.end()
 || iters.second == str2.end()
 || *iters.first == '%')
    // Success […]

Demo.

like image 96
Columbo Avatar answered Sep 20 '22 14:09

Columbo


Here's a hackish way of doing it:

auto it = std::find_if(
  str1.begin(), str1.end(),
  [&str2](const char &c) {
    return c == '%' || str2[&c - &str1[0]] != c
  }
);
bool equal = (it == str1.end() || *it == '%');

The idea is to create a predicate "character is the same as in the other string and not a '%'."

It relies on str2 being long enough, but so does the code in the question.

like image 29
Angew is no longer proud of SO Avatar answered Sep 19 '22 14:09

Angew is no longer proud of SO