Problem Statement - Sentence to Title Case Conversion
Write a program in Java to accept a string in lower case and change the first letter of every word to upper case. Display the new string.
Sample input: we are in cyber world
Sample output: We Are In Cyber World
Solution
TC++ #7192
Run Output
Enter a sentence: we are in cyber world
Output: We Are In Cyber World
import java.util.Scanner;
public class SentenceCase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a sentence: “);
String sentence = scanner.nextLine();
String output = “”;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (i == 0 || sentence.charAt(i – 1) == ‘ ‘) {
output = output + Character.toUpperCase(ch);
} else {
output = output + ch;
}
}
System.out.println(“Output: ” + output);
}
}
— OR —
import java.util.*;
class ConvertToTitleCase
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter a sentence: “);
String ip=sc.nextLine();
ip+=” “; //To handle word boundary for last word also
String op=””;
String word=””;
for(int i=0;i<ip.length();i++)
{
char c=ip.charAt(i);
if(c != ‘ ‘) word+=c;
else
{
op+=Character.toUpperCase(word.charAt(0));
op+=word.substring(1)+” “;
word=””;
}
}
System.out.println(“Output: “+op);
}
}