Capitalize the first and last letter of every word in a string

Problem statement:- Program to Capitalize the first and last letter of every word in a string.

Data requirement:-

   Input Data:- str

  Output Data:-str

  Additional Data:- i

Program in C

Here is the source code of the C Program to Capitalize the first and last letter of every word in a string.

Code:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
    char str[30];
    printf("Enter your String:");
    scanf("%[^\n]",str);
    int i=0;
    for(i=0;i<strlen(str);i++)
    {
    if(i==0 || str[i-1]==' ')
    {
        str[i]=toupper(str[i]);
    }
    else if(str[i+1]==' ' || str[i+1]=='\0')
        str[i]=toupper(str[i]);
    }
    printf("After Converting String is:%s",str);
}

Input/Output:
Enter your String:cs info com
After Converting String is:CS InfO CoM

Program in C++

Here is the source code of the C++ Program to Capitalize the first and last letter of every word in a string.

Code:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    string str;
    cout<<"Enter your String:";
    getline(cin,str);
    int i=0;
    int len=0;
    while(str[len]!='\0')
    {
        len++;
    }
    for(i=0;i<len;i++)
    {
    if(i==0 || str[i-1]==' ')
    {
        str[i]=toupper(str[i]);
    }
    else if(str[i+1]==' ' || str[i+1]=='\0')
        str[i]=toupper(str[i]);
    }
    cout<<"After Converting String is: "<<str;
}

Input/Output:
Enter your String:c plus plus java
After Converting String is: C PluS PluS JavA

Program in Java

Here is the source code of the Java Program to Capitalize the first and last letter of every word in a string.

Code:

import java.util.Scanner;
public class p10 {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
String str1;
System.out.println("Enter your String:");
str1=cs.nextLine();
str1+='\0';
char[] str=str1.toCharArray();
for(int i=0;i<str1.length();i++)
    {
if(i==0 || str[i-1]==' ')
    {
    str[i]=Character.toUpperCase(str[i]);
    }
else if(str[i]==' ' || str[i]=='\0')
    str[i-1]=Character.toUpperCase(str[i-1]);
    }
System.out.print("After Converting String is: ");
for(int i=0;i<str1.length();i++)
System.out.print(str[i]);
cs.close();
}
}

Input/Output:
Enter your String:
string interview question
After Converting String is: StrinG IntervieW QuestioN

Program in Python

Here is the source code of the Python Program to Capitalize the first and last letter of every word in a string.

Code:

ch=input("Enter the String:")
j=0
str=list(ch)
str+='\0'
for i in range(len(str)):
    if i==0 or str[i-1]==' ':
        str[i]=str[i].upper()
    elif str[i]==' ' or str[i]=='\0':
        str[i-1] = str[i-1].upper()

print("Your String is:", "".join(str))

Input/Output:

Post a Comment

0 Comments