How can I find if a string ends with another string in C++?
相关问题
- Sorting 3 numbers without branching [closed]
- 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
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
you can use string::rfind
The full Example based on comments:
Simply compare the last n characters using
std::string::compare
:The
std::mismatch
method can serve this purpose when used to backwards iterate from the end of both strings:Note, that starting from c++20 std::string will finally provide starts_with and ends_with. Seems like there is a chance that by c++30 strings in c++ might finally become usable, if you aren't reading this from distant future, you can use these startsWith/endsWith:
and some extra helper overloads:
IMO, c++ strings are clearly dysfunctional, and weren't made to be used in real world code. But there is a hope that this will get better at least.
Let
a
be a string andb
the string you look for. Usea.substr
to get the last n characters ofa
and compare them to b (where n is the length ofb
)Or use
std::equal
(include<algorithm>
)Ex:
the very same as above, here is my solution