Hello
I am challenging myself to try to attempt to write a function that is as efficient, portable and failsafe as possible. The function is very simple and just converts a string (or wstring) to lower case. Are there any improvements you think I could make and any errors I have done?
#ifdef UNICODE
typedef std::wstring tstring;
typedef std::wstring::npos tnpos;
#else
typedef std::string tstring;
//typedef std::string::npos tnpos; // throws compiler error?!
#endif
tstring toLower(const tstring& str)
{
// Alternative 1: Returns a copy of a local string so not that efficient.
unsigned int len = str.length(); // use unsigned int so I only have 4 bytes as opposed to 16 for int
tstring lower(len, 'a'); // ensure string is correct size to avoid dynamic resizing. Reserve at construction; performing 2 steps at once defintion and reserving - is faster right?
// or use lower.reserve(len);
for (unsigned int i=0; i<len; i++) // iterate using indexes. Maybe iterators could be more fail safe/efficient/etc.?
lower[i] = tolower(str[i]);
return lower;
}
void toLower(const tstring& inStr, tstring& outStr)
{
// Alternative 2: Have user define string and pass by reference (this would be faster?)
unsigned int len = inStr.length(); // use unsigned int so I only have 4 bytes as opposed to 16 for int. Store length in local variable because we look it up again in the below for loop
outStr.resize(len); // ensure string is correct size to avoid dynamic resizing.
for (unsigned int i=0; i<len; i++) // iterate using indexes. Maybe iterators could be more fail safe/efficient/etc.?
outStr[i] = tolower(inStr[i]);
}