Tutorialspoint
Problem
Solution
Submissions

Capitalize the first letter of each word

Certification: Basic Level Accuracy: 50% Submissions: 4 Points: 5

Write a C# program to capitalize the first letter of each word in a given sentence. Words are separated by one or more spaces. After capitalization, all other letters in each word should remain in their original case, and the spacing between words should be preserved.

Implement the CapitalizeWords(string sentence) function, which:

  1. Takes a string representing a sentence as input
  2. Returns a new string with the first letter of each word capitalized
Example 1
  • Input: sentence = "hello world"
  • Output: "Hello World"
  • Explanation:
    • The first letter of each word ('h' in "hello" and 'w' in "world") is capitalized.
Example 2
  • Input: sentence = "the quick brown fox"
  • Output: "The Quick Brown Fox"
  • Explanation:
    • The first letter of each word ('t' in "the", 'q' in "quick", 'b' in "brown", 'f' in "fox") is capitalized.
Constraints
  • 0 <= sentence.length <= 500
  • sentence consists of English letters (uppercase and lowercase), digits, and spaces
  • Time Complexity: O(n) where n is the length of the sentence
  • Space Complexity: O(n)
StringsKPMGSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the sentence into words using String.Split()
  • For each word, capitalize the first letter and keep the rest of the word unchanged
  • Use char.ToUpper() for the first character and concatenate with the rest of the word
  • Join all capitalized words back together with spaces
  • Handle edge cases like empty strings or words

Steps to solve by this approach:

 Step 1: Check if the input sentence is null or empty; if so, return it as is
 Step 2: Split the sentence into words by spaces
 Step 3: Iterate through each word in the sentence
 Step 4: For each word, convert the first character to uppercase using char.ToUpper() and keep the rest of the word unchanged
 Step 5: Join all the capitalized words with spaces and return the result

Submitted Code :