Capitalize Each Word
Capitalize the first letter of every word in a sentence.
Sample input
hello world foo
Sample output
Hello World Foo
Solution
s = "hello world foo"
print(s.title())
const s = "hello world foo";
const result = s.split(" ").map(w =>
w.charAt(0).toUpperCase() + w.slice(1)
).join(" ");
console.log(result);
public class Main {
public static void main(String[] args) {
String s = "hello world foo";
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String w = words[i];
sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1));
if (i < words.length - 1) sb.append(" ");
}
System.out.println(sb.toString());
}
}
fun main() {
val s = "hello world foo"
val result = s.split(" ").joinToString(" ") {
it.replaceFirstChar { c -> c.uppercase() }
}
println(result)
}
let s = "hello world foo"
let result = s.split(separator: " ").map { word -> String in
return word.prefix(1).uppercased() + word.dropFirst()
}.joined(separator: " ")
print(result)
void main() {
String s = 'hello world foo';
List<String> words = s.split(' ');
String result = words.map((w) {
return w[0].toUpperCase() + w.substring(1);
}).join(' ');
print(result);
}
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s = "hello world foo";
bool capitalize = true;
for (char &c : s) {
if (c == ' ') {
capitalize = true;
} else if (capitalize) {
c = toupper(c);
capitalize = false;
}
}
cout << s << endl;
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main() {
char s[] = "hello world foo";
int capitalize = 1;
for (int i = 0; s[i]; i++) {
if (s[i] == ' ') {
capitalize = 1;
} else if (capitalize) {
s[i] = toupper(s[i]);
capitalize = 0;
}
}
printf("%s\n", s);
return 0;
}