Re: Function to search a string in a string in reverse order
In article <1182408782.983219.226680@n60g2000hse.googlegroups.com>,
monty <manishgandhi13@gmail.com> wrote:
Hi All,
I came to an scenario where i need a C++ function to search a string
in a string in reverse order.
Problem is like that:
i have a string like "a~!b~!c" . in this string ~! is the seprater
string and i want the values in reverse order. In the application i
can not use the forward search.
So please help me in resolving this.
let me know if you need any other information.
something like this?
class reverse_tokenizer
{
class test
{
char first;
char second;
public:
test(char a,char b):first(b),second(a){}
bool operator () (char x,char y) const
{
return x == first && y==second;
}
};
test is_delimiter;
std::string::const_reverse_iterator rbegin;
std::string::const_reverse_iterator rend;
public:
reverse_tokenizer(const std::string &str,
char first,char second)
:is_delimiter(first,second),rbegin(str.rbegin()),
rend(str.rend()){}
bool done() const {return rbegin==rend;}
std::pair
<
std::string::const_iterator,
std::string::const_iterator
> next()
{
std::string::const_reverse_iterator
it = std::adjacent_find(rbegin,rend,is_delimiter),
jt,kt;
jt = it;
kt = rbegin;
// if a delimiter was found 'advance' past it.
if(it!=rend)
{
++it;
++it;
}
rbegin = it; // rest of string 'begins' here.
// return pair of const_iterators, representing token found
// in original order.
return std::make_pair
(
jt.base(),
kt.base()
);
}
};
reverse_tokenizer tokenizer(str,'~','!');
while(!tokenizer.done())
{
std::pair<...> range = next;
// found token is in range [range.first,range.second).
// use it.
}
longer delimiters requre std::search similiar to above,
one char just needs std::find, both with reverse iterators,
and a similar approach to convert the range of the found token
in original order.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]