Java program to Capitalize the First and Last letter of Each Word of a String
Capitalize the First and Last letter
Today we will look at java program, we’re going to capitalize all the first and last character of the words in a string.
Lets understand with the help of an example.
Input String:- prepinsta
Output String:- PrepinstA

Algorithm
- Take a string input from the user and store it in the variable called “s”.
- Take a “newstr” variable initialize with an empty string.
- Split the string into words and store it in the String array using regex.
- Take a for-each loop and store the first character by using subString() and store it in the “firstchar” and rest of the string store in “restchar” .
- Then add the “firstchar” and “restchar” string in “newstr”.
Note
Take a string input from the user and store it in the variable called "s". Take a new variable "newstr" and initialize it with an empty string. Split the string into words and store it in the String array using regex. Take a for-each loop and store the first character by using subString() and capitalize that first character using upperCase() method and store it in the "firstchar" and rest of the string from 1 to length-1 store in "restchar" , get the last character of string using charAt() method and convert that character to string using toString() and then add the "firstchar" and "restchar" string in "newstr"
Code in Java
import java.util.Scanner; public class CapitalizeTheFirstAndLastLetterOfString { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.print("Enter String : "); String s = sc.nextLine(); String newstr = ""; String[] str = s.split("\\s"); // splitting sentence into word converted to String array for (String string : str) { int length = string.length(); String firstchar = string.substring(0, 1); String restchar = string.substring(1, length - 1); String lastchar = Character.toString(string.charAt(length - 1)); newstr = newstr+firstchar.toUpperCase()+restchar+" "; } System.out.println(newstr); } }
Output
Enter String : prep inst is best
PreP InstA IS BesT
Method 2 (Capitalize the First and Last letter)
class Main { static String FirstAndLast(String str) { // Create an equivalent char array of given string char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // k stores index of first character and i is going to store index of last character. int k = i; while (i < ch.length && ch[i] != ' ') i++; // Check if the character is a small letter If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return new String(ch); } public static void main(String args[]) { String str = "Prep insta"; System.out.println("Input String:- "+str); System.out.println("String after Capitalize the first and last character of each word in a string:- "+FirstAndLast(str)); } }
Output
Input String:- Prep insta String after Capitalize the first and last character of each word in a string:- PreP InstA
Note
The time complexity of above method is o(n) as we are iterating over the string once in the for loop
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment
import java.util.*;
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
// PS : The name of the public class has to be Main for the code to work
public class Main {
static StringBuilder lo(String ss){
char []cc = ss.toCharArray();
StringBuilder word = new StringBuilder();
char [ ] tmp = ss.toCharArray();
int count =0;
for(int i =0;i=0; j–){
if(tmp[j] == ‘ ‘){
tmp[j+1]= Character.toUpperCase(tmp[j+1]);
// System.out.println(“gaat “+tmp[j+1]);
}
}
}
else if(i == ss.length()-1 ) {
// System.out.println(“lasy “+tmp[i]);
tmp[i]= Character.toUpperCase(tmp[i]);
}
}
for(char c: tmp){
// }
word.append(c);
// System.out.println(“ful “+c);
}
return word;
}
public static void main(String[] args) {
String ss =” junnu’s juned and his girl friend”;
StringBuilder got = lo(ss);
System.out.println(“here is the word of you “+got);
}
}
wihtout any String function
import java.util.Scanner;
class captilize{
void captilize_char(String str){
StringBuilder s = new StringBuilder();
int N = str.length();
for(int i=0;i<N;i++){
if(i==0 || i==N-1){
s.append(Character.toUpperCase(str.charAt(i)));
}
else{
s.append(str.charAt(i));
}
}
System.out.print(s+" ");
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
captilize obj = new captilize();
String str = sc.nextLine();
String []arr = str.split(" ");
for(String c : arr){
obj.captilize_char(c);
}
}
}
import java.util.Scanner;
public class CapitalizeFirstLast {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine().toLowerCase();
scan.close();
String str = “”;
str += Character.toUpperCase(s.charAt(0));
for(int i=1;i<s.length()-1;i++){
if(!(s.charAt(i+1) == ' ')){
str += s.charAt(i);
}
}
str += Character.toUpperCase(s.charAt(s.length() – 1));
System.out.print(str);
}
}
//easy way————- in java
import java.util.*;
public class String_prepinsta {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int len=str.length();
String str1=””;
for(int i=0;i<len;i++){
if(i==0){
str1=str1+Character.toUpperCase(str.charAt(0));
}
else if(i==len-1){
str1=str1+Character.toUpperCase(str.charAt(len-1));
}
else{
str1=str1+str.charAt(i);
}
}
System.out.println(str1);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
if (i == 0 || i == s.length() – 1 || s.charAt(i – 1) == ' ' || s.charAt(i + 1) == ' ') {
result.append(Character.toUpperCase(s.charAt(i)));
} else {
result.append(s.charAt(i));
}
}
System.out.println(result.toString());
}
}
package PripInsta.Strings;
public class Capitalize_First_and_last {
public static void main(String[] args) {
String s = “prep inst is best”;
String s1 = “”;
for(int i= 0;i<s.length();i++){
char ch = s.charAt(i);
if(ch != ' ' && (i == 0 || s.charAt(i – 1) == ' ')){
s1 += Character.toUpperCase(ch);
} else if (ch!=' '&&(i==s.length()-1)||s.charAt(i+1)==' ') {
s1+=Character.toUpperCase(ch);
} else {
s1+=ch;
}
}
System.out.println(s1);
}
}
public class CapitilizeFirstLast {
public static void main(String[] args) {
String s =”i am rohan sandip dhobale”;
String newstr = “”;
String[] str = s.split(“\\s”); // splitting sentence into word converted to String array
for (String string : str) {
int length = string.length();
if (length == 1) {
newstr = newstr + string.toUpperCase() + ” “;
} else {
String firstchar = string.substring(0, 1);
String restchar = string.substring(1, length – 1);
String lastchar = Character.toString(string.charAt(length – 1));
newstr = newstr+firstchar.toUpperCase()+restchar+ lastchar.toUpperCase()+” “;
}
}
System.out.println(newstr.trim());
}
}
this small change because when substring length is 1 then they give exception
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
String s=”kavi varshini”;
String[]k=s.split(” “);
for(int i=0;i<k.length;i++)
{
char[]ch=k[i].toCharArray();
ch[0]=Character.toUpperCase(ch[0]);
ch[ch.length-1]=Character.toUpperCase(ch[ch.length-1]);
k[i] = new String(ch);
}
String result = String.join(" ",k);
System.out.println(result);
}
}
Kindly refer to our discord community for all your technical doubts.
package com.weeknd;
import java.util.Scanner;
public class Program11 {
static void find(String st)
{
char[] ar = st.toCharArray();
String t = “”;
if(ar[0]>=’a’&&ar[0]=’a’&&ar[ar.length-1]<='z')
{
ar[ar.length-1]-=32;
}
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i]);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String st = scan.nextLine();
find(st);
}
}
Kindly join our Discord server, our expert mentors will guide you further precisely🙌
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(“Enter the String: “);
Scanner sc=new Scanner(System.in);
String string=sc.nextLine();
String answer=””;
String str[]=string.split(“\\s”);
for(String s:str) {
int length=s.length();
String first=s.substring(0,1);
String rest=s.substring(1,length-1);
String last=s.substring(length-1);
answer+=first.toUpperCase()+rest+last.toUpperCase()+” “;
}
System.out.println(answer);
}
String s=” aj5 8ehf edid c8dr 6gshN “;String r=””;
r=r+Character.toUpperCase(s.charAt(0));
for(int i=1;i<s.length()-1;i++){
if(s.charAt(i+1)==' '|| s.charAt(i-1)==' '){
r=r+Character.toUpperCase(s.charAt(i));
}else{
r=r+s.charAt(i);
}
}
r=r+Character.toUpperCase(s.charAt(s.length()-1));
System.out.print(r);
Join us on our Discord channel if you have any technical query : Discord