880675. Convert Sentence to Camel Case
Medium
Convert Sentence to Camel Case
Slug: convert-sentence-to-camel-case
Difficulty: Medium
Id: 880675
Topic Tags: Strings
Summary
The problem involves converting a given sentence into camel case, where the first letter of each word is capitalized and the rest of the letters are in lowercase. This requires identifying the individual words in the sentence and then capitalizing the first letter of each word.
Detailed Explanation
To solve this problem, we can use a simple algorithm that iterates through the input string and identifies the spaces that separate the words. Once we have identified the words, we can capitalize the first letter of each word and concatenate them together to form the camel case sentence.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultto store the camel case sentence. - Iterate through the input string character by character. For each character:
- If the character is a space, it separates two words. In this case, capitalize the first letter of the next word and add it to the
resultstring. - If the character is not a space, it is part of the current word. Add it to the
resultstring.
- If the character is a space, it separates two words. In this case, capitalize the first letter of the next word and add it to the
- Once we have processed all characters in the input string, return the
resultstring.
Optimized Solutions
Java
public String convertToCamelCase(String sentence) {
StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;
for (char c : sentence.toCharArray()) {
if (Character.isSpaceChar(c)) {
capitalizeNext = true;
} else if (capitalizeNext) {
result.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
result.append(c);
}
}
return result.toString();
}