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

Capitalize The First and Last Letter in java

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”.

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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

19 comments on “Java program to Capitalize the First and Last letter of Each Word of a String”


  • Tejaswi D

    import java.util.*;
    public class Main {
    public static void main(String args[]) {
    Scanner sc =new Scanner(System.in);

    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();
    if(length==1){
    String firstchar = string.substring(0, 1).toUpperCase();
    newstr = newstr+firstchar +” “;
    continue;

    }
    String firstchar1 = string.substring(0, 1).toUpperCase();
    String restchar = string.substring(1, length – 1);
    String lastchar = string.substring(length – 1).toUpperCase();

    newstr = newstr+firstchar1+restchar+lastchar+” “;
    }
    System.out.println(newstr);
    }
    }


  • shyamkumarreddy515425

    public static void capitalizeString(String s)
    {
    String[] str=s.split(” “);
    String result=””;
    for(int i=0;i<str.length;i++)
    {
    char[] ch=str[i].toCharArray();
    int n=ch.length;
    ch[0]=Character.toUpperCase(ch[0]);
    ch[n-1]=Character.toUpperCase(ch[n-1]);
    String str1=new String(ch);
    result=result+str1+" ";

    }
    System.out.println(result);

    }


  • Arya

    import java.util.Scanner;

    public class CapitalizeWords {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.println(“Enter a sentence in lowercase:”);
    String sentence = scanner.nextLine();

    String capitalizedSentence = “”;
    boolean capitalizeNext = true;

    for (int i = 0; i < sentence.length(); i++) {
    char c = sentence.charAt(i);

    if (capitalizeNext && c != ' ') {
    c = Character.toUpperCase(c);
    capitalizeNext = false;
    } else if (c == ' ') {
    capitalizeNext = true;
    }

    capitalizedSentence += c;
    }

    System.out.println("Capitalized sentence: " + capitalizedSentence);

    scanner.close();
    }
    }


  • jay

    public static void main(String[] args) {
    Scanner ip=new Scanner(System.in);
    String str =ip.nextLine();
    char[] s=str.toCharArray();
    s[0]= (char)(s[0]-32);
    for(int i=1;i<s.length-1;i++){
    if((s[i]==' ')){
    s[i+1]=(char)(s[i+1]-32);
    s[i-1]=(char)(s[i-1]-32);
    }
    }
    s[s.length-1]=(char)(s[s.length-1]-32);
    System.out.println(s);
    }


  • Srinjay

    import java.util.Scanner;
    public class techmonastic {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print(“Enter String :”);
    String s = sc.nextLine();
    String [] sp=s.split(“\\s”);
    String newstr=””;
    for(String res:sp)
    {
    String midstr=res.substring(1,res.length()-1);
    String fstr=res.substring(0,1);
    String lstr=res.substring(res.length()-1);
    newstr=newstr+fstr.toUpperCase()+midstr+lstr.toUpperCase()+” “;
    }

    System.out.println(newstr);
    }
    }


  • Anushka

    public static String capitalizeFirstAndLast(String s)
    {

    if(s.length() <=1 ) return s;
    char [] arr = s.toCharArray();

    arr[0] = Character.toUpperCase(arr[0]);
    arr[arr.length-1] = Character.toUpperCase(arr[arr.length-1]);

    for( int i = 1 ; i < arr.length -2 ; i++)
    {
    if(arr[i] == ' '){
    arr[i-1] = Character.toUpperCase(arr[i-1]);
    arr[i+1] = Character.toUpperCase(arr[i+1]);}
    }

    return String.valueOf(arr);

    }


  • Sameer

    wrong code
    Refer below
    package Strings;

    import java.util.Scanner;

    public class Capitalize_the_first_and_last_character_of_each_word_of_a_string_2 {
    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”);

    for (int i = 0; i 1) {
    firstchar = string.substring(0, 1);
    restchar = string.substring(1, length – 1);
    lastchar = Character.toString(string.charAt(length – 1));
    }else {
    singlechar = string.toUpperCase();
    }
    newstr = newstr + firstchar.toUpperCase() + restchar + lastchar.toUpperCase() + singlechar + ” “;
    }
    System.out.println(newstr);
    }
    }


  • Souhardya

    Scanner sc=new Scanner(System.in); String str=sc.nextLine(); String [] arr = str.split(” “); String res=””;
    res+=Character.toUpperCase(str.charAt(0));
    for(int i=1;i<str.length()-1;i++){
    if(str.charAt(i+1)==' '|| str.charAt(i-1)==' ') {
    res+=Character.toUpperCase(str.charAt(i));
    }
    else
    res+=str.charAt(i);
    }
    res+=Character.toUpperCase(str.charAt(str.length()-1));
    System.out.println(res);


  • SIDDHANT

    String s=”prep insta is best”;
    String temp=””;
    String str[]=s.split(” “);
    for(String s1:str)
    {
    for(int i=0;i<s1.length();i++)
    {
    if(i==0 || i==s1.length()-1)
    {
    temp+=String.valueOf(s1.charAt(i)).toUpperCase();
    }
    else
    {
    temp+=s1.charAt(i);
    }
    }
    }
    System.out.println(temp);


  • Jyotiram

    public static void main(String[] args) {
    Scanner sc =new Scanner(System.in);
    System.out.print(“Enter String : “);
    String s = sc.nextLine();
    StringBuilder newString = new StringBuilder();
    String[] str = s.split(“\\s”);
    for (String string : str) {
    int len = string.length();
    String firstChar = string.substring(0,1).toUpperCase();
    String restChar = string.substring(1, len-1);
    char lastChar = Character.toUpperCase(string.charAt(len-1));
    newString.append(firstChar).append(restChar).append(lastChar).append(” “);
    }
    System.out.println(newString);
    }


  • Ganesh

    public static void main(String[] args) {
    String str=”hai preinsta”;
    String[] x=str.split(” “);
    for(int i=0;i<x.length;i++)
    {
    String y=x[i];
    System.out.print(y.substring(0,1).toUpperCase()+y.substring(1,y.length()-1)+y.substring(y.length()-1,y.length()).toUpperCase());
    }
    }


  • chetan

    String s = sc.nextLine();

    String newstr = “”;

    String[] str = s.split(” “); // splitting sentence into word converted to String array

    for (int i=0; i<str.length;i++) {

    newstr = newstr + Character.toUpperCase(str[i].charAt(0));

    for(int j=1; j<str[i].length()-1;j++)

    newstr = newstr + str[i].charAt(j);
    newstr = newstr + Character.toUpperCase(str[i].charAt(str[i].length()-1))+" ";

    }System.out.println(newstr);