I am trying to find a similar function to strstr
that searches a substring starting from the end towards the beginning of the string.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
One possible, if not entirely elegant, implementation might look like:
I don't believe there is in the c string lib, but it would be trivial to write your own, On one condition, you know the length of the string or it is properly terminated.
Though non-standard, strrstr is widely supported and does exactly what you want.
Edit: As @hhafez notes in a comment below, the first solution I posted for this was inefficient and incorrect (because I advanced the pointer by
target_length
which worked fine in my silly test). You can find that version in the edit history.Here is an implementation that starts at the end and works back:
Output:
The standard C library does not have a "reverse strstr" function, so you have to find or write your own.
I came up with a couple of solutions of my own, and added some testing and benchmarking code together with the other functions in this thread. For those curious, running on my laptop (Ubuntu karmic, amd64 architecture) the output looks like this:
Your results may be different and, depending on your compiler and library, the ordering of the results may also be different.
To get the offset (index) of the match from the beginning of the string, use pointer arithmetic:
And now, the larch (note that this is purely in C, I do not know C++ well enough to give an answer for it):
Thanks for your answers! There is one more way which came from the MSDN forum. http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/ed0f6ef9-8911-4879-accb-b3c778a09d94