Linked Questions

Popular Questions

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. Thank you.

Related Questions