Write a program in Java to accept a string in lowercase and change the first letter of every word to uppercase. Display the new string. Sample input: we are in cyber world Sample Output: We Are In Cyber World
Topic: Converting a sentence to title case
Answer
import java.util.Scanner;
class TitleCase { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a string in lowercase : "); String s = sc.nextLine().toLowerCase();
String res = ""; char ch;
for(int i = 0; i < s.length(); i++) { ch = s.charAt(i);
if(i == 0 | | s.charAt(i - 1) == ' ')
res = res + Character.toUpperCase(ch); else res = res + ch; }
System.out.println(res); } }
The whole question is: how do you recognise the first letter of a word?
A character begins a word if EITHER it is the very first character of the string (i == 0) OR the character before it is a space (s.charAt(i - 1) == ' '). Those two cases joined by | | are the entire logic.
The order of the two tests matters. Java evaluates | | from the left and stops as soon as one part is true, so when i is 0 it never evaluates s.charAt(i - 1) — which would be charAt(-1) and would throw an exception. Swapping the order would crash the program on the very first character. This is called short-circuit evaluation, and it is worth naming in your answer.
An alternative approach builds each word separately and capitalises it, but the character-by-character method above is shorter and needs no trailing space.
Trace the sample: w, a, i, c and w are all preceded by a space (or are first), so each is capitalised, giving We Are In Cyber World.
s String - the sentence entered, converted to lowercase res String - the result string built up in title case ch char - holds each character of s in turn i int - loop variable, the index into the string sc Scanner - object used to read input