Exercise:
Write a Java Program to capitalize the first character of each word in a string.
1.Convert First letter to uppercase
Click Here to View the Solution!
public class FisrtLetter {
public static void main(String[] args) {
String name = "codeofcode";
// first substring contains first letter
// second substring contains remaining
String firstLetter = name.substring(0, 1);
String remainingLetters = name.substring(1, name.length());
firstLetter = firstLetter.toUpperCase();
// joining the substrings back
name = firstLetter + remainingLetters;
System.out.println("Name: " + name);
}
}
Click Here to View the Output!
Name: Codeofcode
Click Here to View the Explanation!
- In this program, firstly a
string type
variablename
has been initialized. - The first letter of this variable’s value is retrieved through
substring()
method and stored in astring
variable namedfirstLetter
. - The rest of the characters of
name
variable are retrieved through thesubstring()
method and stored inremainingLetters
variable. toUpperCase()
method is applied to thefirstLetter
variable which transforms the character into an uppercase letter. The result is stored in thefirstLetter
variable.firstLetter
variable andremainingLetters
variables are appended together and stored in a variable calledname
.- This variable
name
is then printed onto the screen.
2.Convert every word of a String to uppercase
Click Here to View the Solution!
public class FirstLetter {
public static void main(String[] args) {
String message = "everyone loves codeOfCode";
char[] charArray = message.toCharArray();
boolean foundSpace = true;
for(int i = 0; i < charArray.length; i++) {
if(Character.isLetter(charArray[i])) {
// check for space before letter
if(foundSpace) {
charArray[i] = Character.toUpperCase(charArray[i]);
foundSpace = false;
}
}
else {
foundSpace = true;
}
}
// convert the char array to the string
message = String.valueOf(charArray);
System.out.println("Message: " + message);
}
}
Click Here to View the Output!
Message: Everyone Loves CodeOfCode
Click Here to View the Explanation!
- In this program, a variable of string type named
message
is initialized. It contains spaces after certain sequence of characters. - message variable is converted into a character array using the method
toCharArray()
. - Initially the
Boolean
variablefoundSpace
is set to true since the character at the beginning has to be capitalized. - A for loop executes till it reaches the end of the character array.
- Inside the loop, a condition checks to see if the character in the array is a letter. If so, it further checks the state of the
foundSpace
. - If
foundSpace
is true then it means the current letter would be capitalized and thenfoundSpace
is set to false. - Incase the character isn’t a letter,
foundSpace
is set to true. - When the loop breaks, the character array is converted into a
string
and is then displayed on the screen.