Reputation: 270
I know there is function
string::find_last_of
But I want to process a large chunk of char* data. I don't want to assign the char* to a string.
I know there is a std function
std::find
But it only can find char* on positive sequence. Is there such a way to find in reverse order? If not in std, is there a way in boost?
Upvotes: 2
Views: 1304
Reputation: 84
For single-character searching, there is std::ranges::find_last
now (unfortunately only in C++23; and there is no std::find_last
counterpart)
https://en.cppreference.com/w/cpp/algorithm/ranges/find_last
Example:
#include<algorithm>
#include<vector>
#include<cassert>
...
std::vector<char> str{ '1','2','2','3','4' };
auto find = std::ranges::find_last(str.begin(), str.end(), '2'); // [last '2', str.end())
assert(find.begin() == str.begin() + 2 && find.end() == str.end());
Upvotes: 0
Reputation: 75815
If you want to search for one character, like std::find()
does, you can use... std::find()
. Take a look at std::reverse_iterator
:
auto foo(char* str, std::size_t size, char to_find)
{
auto rev_it = std::find(std::make_reverse_iterator(str + size),
std::make_reverse_iterator(str),
to_find);
auto it = std::make_reverse_iterator(rev_it);
}
Upvotes: 2
Reputation: 270
There is a function in boost can solve this problem.
boost::algorithm::find_last
example:
char* s = "abcdabc";
cout << boost::algorithm::find_last(s, "b").begin() - s;
Upvotes: 1
Reputation: 597051
Searches for the last subsequence of elements [s_first, s_last) in the range [first, last).
For example
#include <algorithm>
char *data = ...;
char *data_end = data + size;
char toFind = ...;
char *pfind = &toFind;
char *found = std::find_end(data, data_end, pfind, pfind + 1);
if (found != data_end)
...
Upvotes: 3