First and last letter of each word

Last update on January 14 2023 06:23:11 (UTC/GMT +8 hours)

Python String: Exercise-60 with Solution

Write a Python program to capitalize the first and last letters of each word in a given string.

Sample Solution-1:

Python Code:

def capitalize_first_last_letters(str1):
     str1 = result = str1.title()
     result =  ""
     for word in str1.split():
        result += word[:-1] + word[-1].upper() + " "
     return result[:-1]  
     
print(capitalize_first_last_letters("python exercises practice solution"))
print(capitalize_first_last_letters("w3resource"))

Sample Output:

PythoN ExerciseS PracticE SolutioN
W3ResourcE

Pictorial Presentation:

Python String: Capitalize first and last letters of each word of a given string.

Flowchart:

Flowchart: Capitalize first and last letters of each word of a given string

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Sample Solution-2:

Capitalizes the first letter of a string.

  • Use list slicing and str.upper() to capitalize the first letter of the string.
  • Use str.join() to combine the capitalized first letter with the rest of the characters.
  • Omit the lower_rest parameter to keep the rest of the string intact, or set it to True to convert to lowercase.

Python Code:

def capitalize_first_letter(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])
 
print(capitalize_first_letter('javaScript'))
print(capitalize_first_letter('python', True))

Sample Output:

JavaScript
Python

Flowchart:

Flowchart: Capitalize first and last letters of each word of a given string

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the maximum occuring character in a given string.
Next: Write a Python program to remove duplicate characters of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.



Python: Tips of the Day

Casts the provided value as a list if it’s not one:

Example:

def tips_cast(val):
  return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]

print(tips_cast('bar'))
print(tips_cast([1]))
print(tips_cast(('foo', 'bar')))

Output:

['bar']
[1]
['foo', 'bar']


  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises


Python program to capitalize the first and last letter of each word of a string

October 14, 2022

Capitalize the first and last letter of each word of a string

In this python program, we will be changing the case for the first and last character of the string. Changing case in the string doesn’t only change the look of the string but also changes its value in many ways like it change the ASCII value of the character and also changes its sensitivity because when we perform operations on string case sensitivity of a character changes many things like when you match a lowercase a with uppercase it will give false result.

Capitalize the first and last character of each word of a string

Algorithm

  • Step 1:- Start.
  • Step 2:- Take user input.
  • Step 3:- Slice string from 0 to 1 and convert its case to uppercase.
  • Step 4:- Concatenate the string from 1 to length of string – 1.
  • Step 5:- Concatenate last character after converting it to upper case.
  • Step 6:- Print the string.
  • Step 7:- End.

Python program to convert first and last letter of string to Upper-Case

Objective – Write a python program to capitalize the first and last character of each word in a string

#take user input
String = input('Enter the String :')
#start slicing the String
#take 1st character and convert it to upper case
#Concatinate the string with remaning-1 length
#take last character and change it to uppercase and concatinate it to string
String = String[0:1].upper() + String[1:len(String)-1] + String[len(String)-1:len(String)].upper()
#print the String
print(String)

Output

Enter the String :Prepinsta
PrepinstA
def FirstAndLast(string) :
    # Create an equivalent char array of given string
    ch = list(string);
    i = 0 ;
    while i < len(ch):
        # k stores index of first character and i is going to store index of last character.
        k = i;
        while (i < len(ch) and ch[i] != ' ') :
            i += 1;
        # Check if the character is a small letter If yes, then Capitalise
        if (ord(ch[k]) >= 97 and
            ord(ch[k]) <= 122 ):
            ch[k] = chr(ord(ch[k]) - 32);
        else :
            ch[k] = ch[k]
        if (ord(ch[i - 1]) >= 90 and
            ord(ch[i - 1]) <= 122 ):
            ch[i - 1] = chr(ord(ch[i - 1]) - 32);
        else :
            ch[i - 1] = ch[i - 1]
        i += 1
    return "" . join(ch);
if __name__ == "__main__" :
    string = "Prep insta";
    print("Input string "+string);
    print("String after Capitalize the first and last character of each word in a string:- "+FirstAndLast(string));

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

4 comments on “Python program to capitalize the first and last letter of each word of a string”

  • mahesh

    my_string = input(“>”)

    b = my_string[0].upper() + my_string[1:-1] + my_string[-1].upper()
    print(b)

    0

  • Tejal

    s=input()
    result=”
    for i in s.split():
    result =result + i[0].upper()+ i[1:-1] + i[-1].upper() +” ”
    print(result)

    1

  • BHANU

    a=input()
    print(a[0].upper()+a[1:len(a)-1]+a[len(a)-1].upper())

    2

  • 2

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a string, the task is to print the first and last character of each word in a string.
    Examples: 
     

    Input: Geeks for geeks
    Output: Gs fr gs
    
    Input: Computer applications
    Output: Cr as

    Approach 
     

    1. Run a loop from the first letter to the last letter.
    2. Print the first and last letter of the string.
    3. If there is a space in the string then print the character that lies just before space and just after space.

    Below is the implementation of the above approach. 
     

    C++

    #include<bits/stdc++.h>

    using namespace std;

    void FirstAndLast(string str)

    {

        int i;

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

        {

            if (i == 0)

                cout<<str[i];

            if (i == str.length() - 1)

                cout<<str[i];

            if (str[i] == ' ')

            {

                cout<<str[i-1]<<" "<<str[i+1];

            }

        }

    }

    int main()

    {

        string str = "Geeks for Geeks";

        FirstAndLast(str);

    }

    Java

    class GFG {

        static void FirstAndLast(String str)

        {

            int i;

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

                if (i == 0)

                    System.out.print(str.charAt(i));

                if (i == str.length() - 1)

                    System.out.print(str.charAt(i));

                if (str.charAt(i) == ' ') {

                    System.out.print(str.charAt(i - 1)

                                     + " "

                                     + str.charAt(i + 1));

                }

            }

        }

        public static void main(String args[])

        {

            String str = "Geeks for Geeks";

            FirstAndLast(str);

        }

    }

    Python3

    def FirstAndLast(string):

        for i in range(len(string)):

            if i == 0:

                print(string[i], end = "")

            if i == len(string) - 1:

                print(string[i], end = "")

            if string[i] == " ":

                print(string[i - 1],

                      string[i + 1], end = "")

    if __name__ == "__main__":

        string = "Geeks for Geeks"

        FirstAndLast(string)

    C#

    using System;

    class GFG

    {

        static void FirstAndLast(string str)

        {

            int i;

            for (i = 0; i < str.Length; i++)

            {

                if (i == 0)

                    Console.Write(str[i]);

                if (i == str.Length - 1)

                    Console.Write(str[i]);

                if (str[i] == ' ')

                {

                    Console.Write(str[i - 1]

                                    + " "

                                    + str[i + 1]);

                }

            }

        }

        public static void Main()

        {

            string str = "Geeks for Geeks";

            FirstAndLast(str);

        }

    }

    Javascript

    <script>

          function FirstAndLast(str)

          {

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

            {

              if (i == 0)

              document.write(str[i]);

              if (i == str.length - 1)

              document.write(str[i]);

              if (str[i] === " ") {

                document.write(str[i - 1] + " " + str[i + 1]);

              }

            }

          }

          var str = "Geeks for Geeks";

          FirstAndLast(str);

     </script>

    Time Complexity: O(n) where n is the length of the string

    Auxiliary Space: O(1)

    Another Approach:
     

    In this approach we can split the string into words and then iterate through the words. For each word, we can print its first and last character.

    we use stringstream to split the string into words. We then iterate through the words and print the first and last character of each word.

    Implementation of the above approach:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    void FirstAndLast(string str)

    {

        stringstream ss(str);

        string word;

        while (ss >> word) {

            cout << word[0] << word[word.length() - 1] << " ";

        }

    }

    int main()

    {

        string str = "Geeks for Geeks";

        FirstAndLast(str);

    }

    Java

    import java.util.*;

    class Main {

        public static void firstAndLast(String str) {

            StringTokenizer st = new StringTokenizer(str);

            while (st.hasMoreTokens()) {

                String word = st.nextToken();

                System.out.print(word.charAt(0) + "" + word.charAt(word.length() - 1) + " ");

            }

        }

        public static void main(String[] args) {

            String str = "Geeks for Geeks";

            firstAndLast(str);

        }

    }

    Python3

    def FirstAndLast(string):

        words = string.split()

        for word in words:

            print(word[0] + word[-1], end=" ")

    if __name__ == '__main__':

        string = "Geeks for Geeks"

        FirstAndLast(string)

    C#

    using System;

    using System.Linq;

    using System.Collections.Generic;

    class Program {

        static void Main(string[] args)

        {

            string str = "Geeks for Geeks";

            FirstAndLast(str);

        }

        static void FirstAndLast(string str)

        {

            List<string> words = str.Split(' ').ToList();

            foreach(string word in words)

            {

                Console.Write(word[0]);

                Console.Write(word[word.Length - 1]);

                Console.Write(" ");

            }

        }

    }

    Javascript

    function FirstAndLast(str) {

        let words = str.split(" ");

        let output = "";

        for (let i = 0; i < words.length; i++) {

            output += words[i][0] + words[i][words[i].length - 1] + " ";

        }

        console.log(output);

    }

    let str = "Geeks for Geeks";

    FirstAndLast(str);

    Time Complexity: O(N)

    Space Complexity: O(1)

    Like Article

    Save Article

    Given a string which contains N words, This word can be from of single and multiple characters. Our goal is to capitalize the first and last letter of each word. for example.

    Here given code implementation process.

    /*
        Java program for
        Capitalize the first and last letter of each word of a String
    */
    public class Replacement
    {
        public String capitalizeFirstAndLast(String text)
        {
            int n = text.length();
            if (n == 1)
            {
                // When have less than one character
                return text.toUpperCase();
            }
            if (n == 2)
            {
                // When only two characters
                return text.substring(0, 1).toUpperCase() + 
                  text.substring(1, 2).toUpperCase();
            }
            return text.substring(0, 1).toUpperCase() + 
              text.substring(1, n - 1) + 
              text.substring(n - 1, n).toUpperCase();
        }
        public void changeWord(String text)
        {
            // Get the length
            int n = text.length();
            if (n == 0)
            {
                return;
            }
            // Collecting words
            String[] word = text.split(" ");
            String result = "";
            for (int i = 0; i < word.length; ++i)
            {
                if (i != 0)
                {
                    result += " " + capitalizeFirstAndLast(word[i]);
                }
                else
                {
                    result = capitalizeFirstAndLast(word[i]);
                }
            }
            // Display given text
            System.out.println("Given Text : " + text);
            // Display calculated result
            System.out.println(result);
        }
        public static void main(String[] args)
        {
            Replacement task = new Replacement();
            String text = "this is real";
            task.changeWord(text);
            text = "make a good code";
            task.changeWord(text);
        }
    }

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    package main
    import "fmt"
    import "strings"
    /*
        Go program for
        Capitalize the first and last letter of each word of a String
    */
    type Replacement struct {}
    func getReplacement() * Replacement {
        var me *Replacement = &Replacement {}
        return me
    }
    func(this Replacement) capitalizeFirstAndLast(text string) string {
        var n int = len(text)
        if n == 1 {
            // When have less than one character
            return strings.ToUpper(text)
        }
        if n == 2 {
            // When only two characters
            return strings.ToUpper(string(text[0])) + 
                    strings.ToUpper(string(text[1]))
        }
        return strings.ToUpper(string(text[0])) + 
            text[1 : n - 1] + 
            strings.ToUpper(string(text[n-1]))
    }
    func(this Replacement) changeWord(text string) {
        // Get the length
        var n int = len(text)
        if n == 0 {
            return
        }
        // Collecting words
        var word = strings.Split(text, " ")
        var result string = ""
        for i := 0 ; i < len(word) ; i++ {
            if i != 0 {
                result += " "+ this.capitalizeFirstAndLast(word[i])
            } else {
                result = this.capitalizeFirstAndLast(word[i])
            }
        }
        // Display given text
        fmt.Println("Given Text : ", text)
        // Display calculated result
        fmt.Println(result)
    }
    func main() {
        var task * Replacement = getReplacement()
        var text string = "this is real"
        task.changeWord(text)
        text = "make a good code"
        task.changeWord(text)
    }

    Output

    Given Text :  this is real
    ThiS IS ReaL
    Given Text :  make a good code
    MakE A GooD CodE
    
    // Include namespace system
    using System;
    /*
        Csharp program for
        Capitalize the first and last letter of each word of a String
    */
    public class Replacement
    {
        public String capitalizeFirstAndLast(String text)
        {
            int n = text.Length;
            if (n == 1)
            {
                // When have less than one character
                return text.ToUpper();
            }
            if (n == 2)
            {
                // When only two characters
                return text.ToUpper();
            }
            return text.Substring(0, 1 ).ToUpper() + 
              text.Substring(1, n - 2 ) + text.Substring(n - 1, 1 ).ToUpper();
        }
        public void changeWord(String text)
        {
            // Get the length
            int n = text.Length;
            if (n == 0)
            {
                return;
            }
            // Collecting words
            String[] word = text.Split(" ");
            String result = "";
            for (int i = 0; i < word.Length; ++i)
            {
                if (i != 0)
                {
                    result += " " + this.capitalizeFirstAndLast(word[i]);
                }
                else
                {
                    result = this.capitalizeFirstAndLast(word[i]);
                }
            }
            // Display given text
            Console.WriteLine("Given Text : " + text);
            // Display calculated result
            Console.WriteLine(result);
        }
        public static void Main(String[] args)
        {
            Replacement task = new Replacement();
            String text = "this is real";
            task.changeWord(text);
            text = "make a good code";
            task.changeWord(text);
        }
    }

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    <?php
    /*
        Php program for
        Capitalize the first and last letter of each word of a String
    */
    class Replacement
    {
        public  function capitalizeFirstAndLast($text)
        {
            $n = strlen($text);
            if ($n == 1)
            {
                // When have less than one character
                return strtoupper($text);
            }
            if ($n == 2)
            {
                // When only two characters
                return strtoupper(substr($text, 0, 1)).strtoupper(
                  substr($text, 1, 2 - 1));
            }
            return strtoupper(substr($text, 0, 1 )).substr(
              $text, 1, $n - 2).strtoupper(substr($text, $n - 1, 1));
        }
        public  function changeWord($text)
        {
            // Get the length
            $n = strlen($text);
            if ($n == 0)
            {
                return;
            }
            // Collecting words
            $word = explode(" ", $text);
            $result = "";
            for ($i = 0; $i < count($word); ++$i)
            {
                if ($i != 0)
                {
                    $result .= " ".$this->capitalizeFirstAndLast($word[$i]);
                }
                else
                {
                    $result = $this->capitalizeFirstAndLast($word[$i]);
                }
            }
            // Display given text
            echo("Given Text : ".$text."n");
            // Display calculated result
            echo($result."n");
        }
    }
    
    function main()
    {
        $task = new Replacement();
        $text = "this is real";
        $task->changeWord($text);
        $text = "make a good code";
        $task->changeWord($text);
    }
    main();

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    /*
        Node JS program for
        Capitalize the first and last letter of each word of a String
    */
    class Replacement
    {
        capitalizeFirstAndLast(text)
        {
            var n = text.length;
            if (n == 1)
            {
                // When have less than one character
                return text.toUpperCase();
            }
            if (n == 2)
            {
                // When only two characters
                return text.substring(0, 1).toUpperCase() + 
                  text.substring(1, 2).toUpperCase();
            }
            return text.substring(0, 1).toUpperCase() + 
              text.substring(1, n - 1) + text.substring(n - 1, n).toUpperCase();
        }
        changeWord(text)
        {
            // Get the length
            var n = text.length;
            if (n == 0)
            {
                return;
            }
            // Collecting words
            var word = text.split(" ");
            var result = "";
            for (var i = 0; i < word.length; ++i)
            {
                if (i != 0)
                {
                    result += " " + this.capitalizeFirstAndLast(word[i]);
                }
                else
                {
                    result = this.capitalizeFirstAndLast(word[i]);
                }
            }
            // Display given text
            console.log("Given Text : " + text);
            // Display calculated result
            console.log(result);
        }
    }
    
    function main()
    {
        var task = new Replacement();
        var text = "this is real";
        task.changeWord(text);
        text = "make a good code";
        task.changeWord(text);
    }
    main();

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    #    Python 3 program for
    #    Capitalize the first and last letter of each word of a String
    class Replacement :
        def capitalizeFirstAndLast(self, text) :
            n = len(text)
            if (n == 1) :
                #  When have less than one character
                return text.upper()
            
            if (n == 2) :
                #  When only two characters
                return text[0: 1].upper() + text[1: 2].upper()
            
            return text[0: 1].upper() + text[1: n-1] + text[n - 1: n].upper()
        
        def changeWord(self, text) :
            #  Get the length
            n = len(text)
            if (n == 0) :
                return
            
            #  Collecting words
            word = text.split(" ")
            result = ""
            i = 0
            while (i < len(word)) :
                if (i != 0) :
                    result += " " + self.capitalizeFirstAndLast(word[i])
                else :
                    result = self.capitalizeFirstAndLast(word[i])
                
                i += 1
            
            #  Display given text
            print("Given Text : ", text)
            #  Display calculated result
            print(result)
        
    
    def main() :
        task = Replacement()
        text = "this is real"
        task.changeWord(text)
        text = "make a good code"
        task.changeWord(text)
    
    if __name__ == "__main__": main()

    Output

    Given Text :  this is real
    ThiS IS ReaL
    Given Text :  make a good code
    MakE A GooD CodE
    #    Ruby program for
    #    Capitalize the first and last letter of each word of a String
    class Replacement 
        def capitalizeFirstAndLast(text) 
            n = text.length
            if (n == 1) 
                #  When have less than one character
                return text.upcase
            end
    
            if (n == 2) 
                #  When only two characters
                return text[0].upcase + text[1].upcase
            end
    
            return text[0].upcase + text[1...(n - 1)] + text[n - 1].upcase
        end
    
        def changeWord(text) 
            #  Get the length
            n = text.length
            if (n == 0) 
                return
            end
    
            #  Collecting words
            word = text.split(" ")
            result = ""
            i = 0
            while (i < word.length) 
                if (i != 0) 
                    result += " "+ self.capitalizeFirstAndLast(word[i])
                else
     
                    result = self.capitalizeFirstAndLast(word[i])
                end
    
                i += 1
            end
    
            #  Display given text
            print("Given Text : ", text, "n")
            #  Display calculated result
            print(result, "n")
        end
    
    end
    
    def main() 
        task = Replacement.new()
        text = "this is real"
        task.changeWord(text)
        text = "make a good code"
        task.changeWord(text)
    end
    
    main()

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    
    import scala.collection.mutable._;
    /*
        Scala program for
        Capitalize the first and last letter of each word of a String
    */
    class Replacement()
    {
        def capitalizeFirstAndLast(text: String): String = {
            var n: Int = text.length();
            if (n == 1)
            {
                // When have less than one character
                return text.toUpperCase();
            }
            if (n == 2)
            {
                // When only two characters
                return text.substring(0, 1).toUpperCase() + 
                  text.substring(1, 2).toUpperCase();
            }
            return text.substring(0, 1).toUpperCase() + 
              text.substring(1, n - 1) + text.substring(n - 1, n).toUpperCase();
        }
        def changeWord(text: String): Unit = {
            // Get the length
            var n: Int = text.length();
            if (n == 0)
            {
                return;
            }
            // Collecting words
            var word: Array[String] = text.split(" ");
            var result: String = "";
            var i: Int = 0;
            while (i < word.length)
            {
                if (i != 0)
                {
                    result += " " + capitalizeFirstAndLast(word(i));
                }
                else
                {
                    result = capitalizeFirstAndLast(word(i));
                }
                i += 1;
            }
            // Display given text
            println("Given Text : " + text);
            // Display calculated result
            println(result);
        }
    }
    object Main
    {
        def main(args: Array[String]): Unit = {
            var task: Replacement = new Replacement();
            var text: String = "this is real";
            task.changeWord(text);
            text = "make a good code";
            task.changeWord(text);
        }
    }

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE
    import Foundation;
    /*
        Swift 4 program for
        Capitalize the first and last letter of each word of a String
    */
    class Replacement
    {
        func getMiddle(_ text: [Character]) -> String
        {
            var i = 1;
            var value = "";
            while (i < text.count - 1)
            {
                value += String(text[i]);
                i+=1;
            }
          return value;
        }
        func capitalizeFirstAndLast(_ text: [Character]) -> String
        {
            let n: Int = text.count;
            if (n == 1)
            {
                // When have less than one character
                return String(text[0]).uppercased();
            }
            if (n == 2)
            {
                // When only two characters
                return String(text[0]).uppercased() + String(text[1]).uppercased();
            }
            return String(text[0]).uppercased() + 
              getMiddle(text) + String(text[n - 1]).uppercased();
    }
    func changeWord(_ text: String)
    {
        // Get the length
        let n: Int = text.count;
        if (n == 0)
        {
            return;
        }
        // Collecting words
        let word: [String] = text.split
        {
            $0 == " "
        }.map(String.init);
        var result: String = "";
        var i: Int = 0;
        while (i < word.count)
        {
            if (i  != 0)
            {
                result += " " + self.capitalizeFirstAndLast(Array(word[i]));
            }
            else
            {
                result = self.capitalizeFirstAndLast(Array(word[i]));
            }
            i += 1;
        }
        // Display given text
        print("Given Text : ", text);
        // Display calculated result
        print(result);
    }
    }
    func main()
    {
        let task: Replacement = Replacement();
        var text: String = "this is real";
        task.changeWord(text);
        text = "make a good code";
        task.changeWord(text);
    }
    main();

    Output

    Given Text :  this is real
    ThiS IS ReaL
    Given Text :  make a good code
    MakE A GooD CodE
    /*
        Kotlin program for
        Capitalize the first and last letter of each word of a String
    */
    class Replacement
    {
        fun capitalizeFirstAndLast(text: String): String 
        {
            val n: Int = text.length;
            if (n == 1)
            {
                // When have less than one character
                return text.toUpperCase();
            }
            if (n == 2)
            {
                // When only two characters
                return text.toUpperCase();
            }
            return text.substring(0, 1).toUpperCase() + 
              text.substring(1, n - 1) + text.substring(n - 1, n).toUpperCase();
        }
        fun changeWord(text: String): Unit
        {
            // Get the length
            val n: Int = text.length;
            if (n == 0)
            {
                return;
            }
            // Collecting words
            val word = text.split(" ");
            var result: String = "";
            var i: Int = 0;
            while (i < word.count())
            {
                if (i != 0)
                {
                    result += " " + this.capitalizeFirstAndLast(word[i]);
                }
                else
                {
                    result = this.capitalizeFirstAndLast(word[i]);
                }
                i += 1;
            }
            // Display given text
            println("Given Text : " + text);
            // Display calculated result
            println(result);
        }
    }
    fun main(args: Array < String > ): Unit
    {
        val task: Replacement = Replacement();
        var text: String = "this is real";
        task.changeWord(text);
        text = "make a good code";
        task.changeWord(text);
    }

    Output

    Given Text : this is real
    ThiS IS ReaL
    Given Text : make a good code
    MakE A GooD CodE

    Home »
    Interview coding problems/challenges

    In this article, we are going to learn how to capitalize first and last letter of each word in an input line?
    Submitted by Radib Kar, on November 27, 2018

    Problem statement:

    Given an input line, capitalize first and last letter of each word in the given line. It’s provided that the input line is in lowercase.

    Solution:

    The basic algorithm is to keep track of the spaces and to capitalize the letter before space & after space. Also, the first letter and the last letter of the line should be capitalized.

    Few more things that need to be kept in mind such that:

    1. More than one occurrence of space in between two words.
    2. There may be word of single letter like ‘a’, which need to be capitalized.
    3. There may be word of two letters like ‘me’, where both the letters need to be capitalized.

    Algorithm:

    1. Create a hash table.
    2. Insert index of first letter, i.e., 0 & the index of last letter, i.e., length-1. length be the length of input line.
    3.     For i=0:length-1
          Find index of spaces in the line
          If index before spaces are not in hash table
              Insert into hash table
          If index after spaces are not in hash table
              Insert into hash table
      
    4. Capitalize the indexes present in the hash table
      line [index]-=32;
    5. //ASCII value of lower case letter — ASCII value of corresponding upper case letter=32
    6. Print the converted input line

    Inclusion of hash table in the program helps us to avoid inserting duplicate indexes. Otherwise, corner test-cases may fail.

    C++ program to capitalize first and last letter of each word in a line

    #include <bits/stdc++.h>
    using namespace std;
    
    void capitalize(char* arr,int i){
    	//ascii value of each lower case letter-ascii value 
    	//of each uppercase letter=32
    	//i is the length of line
    	unordered_set<int> table;
    	table.insert(0); //index of first letter of line
    	table.insert(i-1);//index of last letter of line
    	
    	for(int j=1;j<i;j++){
    		if(arr[j]==' '){
    			// last letter of word is before 
    			//space & first letter of word is after space
    			//check index already present in hash table or not
    			if(table.find(j-1)==table.end())
    				table.insert(j-1); //if not insert index
    			//check index already present in hash table or not
    			if(table.find(j+1)==table.end())			
    				table.insert(j+1); //if not insert index
    		}
    	}
    	//capitalize
    	for(auto it=table.begin();it!=table.end();it++)
    		arr[*it]-=32;
    	printf("converted input line is: ");
    	//printing 
    	for(int j=0;j<i;j++)
    		printf("%c",arr[j]);
    	printf("n");
    }
    
    int main(){
    	//store the input line
    	char arr[100];
    	char c;
    	int i=0;
    
    	printf("input the line.....n");
    	scanf("%c",&c);
    	while(c!='n'){
    		arr[i++]=c;
    		scanf("%c",&c);
    	}
    	capitalize(arr,i);
    	
    	return 0;
    }
    

    Output

    First run:
    input the line.....
    hello world
    converted input line is: HellO WorlD
    
    Second run:
    input the line.....
    includehelp is a great paltform for geeks
    converted input line is: IncludehelP IS A GreaT PaltforM FoR GeekS 
    

    Понравилась статья? Поделить с друзьями:
  • Fireworks one word or two
  • Firefox не открывает word
  • Firefox word to pdf
  • Firefighter is one word
  • Fired for using the n word