0

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?
UFColonel
  • 23
  • 3

1 Answers1

0

I specifically allocated the length of the text + 1

There's your hint - what is the length of the text?

Change this:

        for (int i = 0; *(text + i) != '\0'; i++)
            arr[i] = *(text + i);

To this:

        for (int i = 0; *(text + i) != '\0'; i++)
            printf("%c", *(text + i));

And it will answer your question

In other words, you did not properly terminate your input string with a null character.

goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • It would be more suitable as a comment, but I couldn't "fit it in" properly... – goodvibration Oct 25 '20 at 08:58
  • Thanks so much, @goodvibration ! Yeah, I completely forgot about that ! I just got my mind on this little bugger for 2 straight days and I finally conceded today just to see that I forgot to assing the null on the last element. – UFColonel Oct 25 '20 at 09:04