Search code examples
c#stringuppercase

How to Fix: Uppercase first letter of every word in the string - except for one letter words


I have a code to capitalize the first letter of every words except for one letter words.

The problem I have is if the last word of that string is one letter, it gives a index out of range exception. Which makes sense because the code array[i + 1] doesn't exist for the last letter.

static string UppercaseWords(string value)
{
    char[] array = value.ToLower().ToCharArray();
    // Handle the first letter in the string.

    array[0] = char.ToUpper(array[0]);
    // Scan through the letters, checking for spaces.
    // ... Uppercase the lowercase letters following spaces.
    for (int i = 1; i < array.Length; i++)
    {
        if (array[i - 1] == ' ' && array[i + 1] != ' ') 
        {
            array[i] = char.ToUpper(array[i]);
        }
    }
    return new string(array);
}

I'm just looking for something to get around that exception, or another way to do this.


Solution

  • You can improve condition so you will not ask for the (i+1)-th index.

    if (array[i - 1] == ' ' && i + 1 < array.Length && array[i + 1] != ' ')