I had a need to do a case insensitive find and found the following code which did the trick
bool ci_equal(char ch1, char ch2)
{
return toupper((unsigned char)ch1) == toupper((unsigned char)ch2);
}
size_t ci_find(const string& str1, const string& str2)
{
string::const_iterator pos = std::search(str1. begin ( ), str1. end ( ), str2.
begin ( ), str2. end ( ), ci_equal);
if (pos == str1. end ( ))
return string::npos;
else
return pos - str1. begin ( );
}
That got me to wondering what it would take to make this a member function of 'string' so it could be called like this:
string S="abcdefghijklmnopqrstuv";
string F="GHI";
S.ci_find(F);
I realize that there are many problems with case conversions in non-English languages but that's not the question I'm interested in.
Being a neophyte, I quickly got lost among containers and templates.
Is there anyway to do this? Could someone point to me an example of something similar?
Extension methods are your best bet. They have the same feel as instance methods without the cost of inheritance. public static class Extensions { public static bool contains(this string source, bool ignoreCase) {... } }
C++ String append() This function is used to extend the string by appending at the end of the current value.
In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.
The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.
I think most more experienced C++ programmers would agree that this is poor idea. If anything, std::string
already has way too many member functions, and adding still more will make a bad situation worse. Worse still, if you were going to do this, you'd probably do it by inheritance -- but std::string
isn't designed to be used as a base class, and using it as one will lead to code that's fragile and error-prone.
For another idea of how to do this, you might want to read Guru of the Week #29. Do read the whole article though, to get an idea of both how to do it, and why you probably don't want to. Ultimately, what you have right now is probably the best option -- keep the case insensitive searching separate from std::string
itself.
std::string
is not made to be extended.
You could encapsulate an std::string into a class of yours and set those member functions in that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With