I am originally a Java programmer and I have a deep love of the syntax, especially regarding the String
object. With C++, I have tried to recreate the toUpperCase()
method that Java has. The only problem is that it always returns a String
object that has an empty/NULL char array.
String String::toUpperCase()
{
char *a = new char[this->length + 1];
memset(a, 0, this->capacity + 1);
memcpy(a, this->characters, this->length);
for (int i = 0; i < strlen(this->characters); i++)
{
toupper(a[i]);
}
return *new String(a);
}
You have a few memory problems with your attempt, as well as a logical one. All you need to return a copy of a string with the characters being upper case is:
std::string str = "My Original string";
std::string myCopy(str);
std::locale loc;
std::transform(myCopy.begin(), myCopy.end(), myCopy.begin(), [&](char c)
{
return std::toupper(c, loc);
});