Write a Program to Capitalize the first and last letter of each word of a string

27 June 2022

Write a Program to Capitalize the first and last letter of each word of a string


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a string from the user and then change the first and last letter to uppercase.

 

Input

programming

Output

ProgramminG

C Program

#include<stdio.h>

#include <ctype.h>

#include<string.h>

int main()

{

  char str[20];

  int length = 0;

  printf("Enter a string: ");

  scanf("%s",str);

  length = strlen(str);

  for(int i=0;i<length;i++)

  {

      if(i==0||i==(length-1))

      {

          str[i]=toupper(str[i]);

      }

      else if(str[i]==' ')

      {

          str[i-1]=toupper(str[i-1]);

          str[i+1]=toupper(str[i+1]);

      }

  }

  printf("After conversion of first and last letter to uppercase: %s", str);

  return 0;

}

 

 

 

C++ Program

#include<iostream>

#include <ctype.h>

#include<string.h>

using namespace std;

int main()

{

  char str[20];

  int length = 0;

  cout<<"Enter a string: ";

  cin>>str;

  length = strlen(str);

  for(int i=0;i<length;i++)

  {

      if(i==0||i==(length-1))

      {

          str[i]=toupper(str[i]);

      }

      else if(str[i]==' ')

      {

          str[i-1]=toupper(str[i-1]);

          str[i+1]=toupper(str[i+1]);

      }

  }

  cout<<"After conversion of first and last letter to uppercase: "<<str;

  return 0;

}

 

 

Java

import java.util.Scanner;

public class Main

{

              public static void main(String[] args) {

                             Scanner sc =new Scanner(System.in);

     System.out.print("Enter a string : ");

     String str = sc.nextLine();

     String newstring = "";

     String[] str1 = str.split("\\s");

    for (String string : str1) {    

      int length = string.length();

      String f = string.substring(0, 1);

      String r = string.substring(1, length - 1);

      String l = Character.toString(string.charAt(length-1));

      newstring = newstring+f.toUpperCase()+r+l.toUpperCase();

    }

    System.out.println(newstring);

              }

}

 

Python

Str1 = input('Enter a string: ')

Str1 = Str1[0:1].upper() + Str1[1:len(Str1)-1] + Str1[len(Str1)-1:len(Str1)].upper()

print(Str1)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !