Capitalize Each Word
Problem
Read one line where words are separated by single spaces. Make the first letter of each word upper case and the other letters lower case.
Constraints
- 1 <= length <= 10^5, single spaces, ASCII
Examples
Input
hello wORLD
Output
Hello World
Solutions
We split the line, fix each word (first letter up, rest down) and join the words again.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : Capitalize words.
* Approach: Split, fix, join.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String s) {
// Step 1: Split the line into words.
String[] words = s.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
// Step 2: First letter in upper case, the rest in lower case.
if (word.length() > 0) {
result.append(Character.toUpperCase(word.charAt(0)));
result.append(word.substring(1).toLowerCase());
}
// Step 3: One space between words.
if (i < words.length - 1) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- How do you get all letters except the first?