I'm trying to create a char* toTitleCase(char* text)
function that makes every word in a text start with a capital letter.
Here is my current code:
char* toTitleCase(char* text)
{
char* arr = new char[strlen(text) + 1];
for (int i = 0; *(text + i) != '\0'; i++)
arr[i] = *(text + i);
// Example: arr is now "salut. ce mai faciCCCCCCCCCC"
for(int i = 0 ; arr[i] != '\0' ; i++)
{
// Make the first letter capital if it isn't.
if (i == 0 && (arr[i] >= 97 && arr[i] <= 122))
arr[i] = arr[i] - 32;
// Check for a blank space. If found, check the next char and make it capital.
else if (arr[i] == ' ' && (arr[i + 1] >= 97 && arr[i + 1] <= 'z'))
arr[i+1] = arr[i+1] - 32;
}
// Example: arr is : "Salut. Ce Mai FaciCCCCCCCCCC"
return arr;
delete[] arr;
// Example Google C++ Test :
//Expected: "Salut. Ce Mai Faci"
// Got : "Salut. Ce Mai FaciCCCCCCCCCC"
}
My questions:
- Why do I get the "CCCCC" at the end if I specifically allocated the length of the text + 1 ?
- How can I solve this issue?