-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-8_Capitalize_First_Letter_of_Each_Word.js
More file actions
53 lines (45 loc) · 2.09 KB
/
Problem-8_Capitalize_First_Letter_of_Each_Word.js
File metadata and controls
53 lines (45 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Problem-8_Capitalize_First_Letter_of_Each_Word with Solution, Explanation, Verification, and Execution:
// To capitalize first letter of each word, we can implement the Solution like below:
// -------------------------------------------------------------------
function capitalizeWords(sentence) {
let result = '';
let capitalizeNext = true;
for (let char of sentence) {
if (capitalizeNext && char >= 'a' && char <= 'z') {
result += char.toUpperCase();
capitalizeNext = false;
} else {
result += char;
if (char === ' ') {
capitalizeNext = true;
}
}
}
return result;
}
// Explanation:
// ---------------
// The function builds a result string incrementally and uses a flag to track when to capitalize (initially true). It loops through each character: if the flag is true and the character is lowercase, it uppercases and adds it, then resets the flag. Otherwise, it adds the character as is and sets the flag to true if encountering a space (indicating the start of a new word). This character-by-character processing handles capitalization without splitting the string into words.
// Verification:
// ----------------
// function capitalizeWords(sentence) {
// let result = '';
// let capitalizeNext = true;
// for (let char of sentence) {
// if (capitalizeNext && char >= 'a' && char <= 'z') {
// result += char.toUpperCase();
// capitalizeNext = false;
// } else {
// result += char;
// if (char === ' ') {
// capitalizeNext = true;
// }
// }
// }
// return result;
// }
// console.log(capitalizeWords("hello world"));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-8_Capitalize_First_Letter_of_Each_Word.js'
// Output (In the directory in IDE environment with node.js installed): "Hello World"