The Wayback Machine - https://web.archive.org/web/20240901091952/https://www.geeksforgeeks.org/capitalise-the-first-and-last-character-of-each-word-in-a-string/
Open In App

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

Last Updated : 07 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Basic
38.13%
44.3K

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

Input: Geeks for geeks
Output: GeekS FoR GeekS

Input: Geeksforgeeks is best
Output: GeeksforgeekS IS BesT

Approach 
 

  • Create a character array of the String
  • Run a loop from the first letter to the last letter.
  • Check if the character is the starting or end of the word
  • Check if the character is a small letter.
  • If yes, then Capitalise the character of the string.

Below is the implementation of the above approach. 
 

C++




// CPP program to capitalise the first
// and last character of each word in a string.
#include<bits/stdc++.h>
using namespace std;
 
string FirstAndLast(string str)
{
 
    // Create an equivalent string
    // of the given string
    string ch = str;
    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 ch;
}
 
// Driver code
int main()
{
    string str = "Geeks for Geeks";
    cout << str << "\n";
    cout << FirstAndLast(str);
}
 
// This code is contributed by ihritik


Java




// Java program to capitalise the first
// and last character of each word in a string.
 
class GFG {
    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);
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str = "Geeks for Geeks";
        System.out.println(str);
        System.out.println(FirstAndLast(str));
    }
}


Python3




# Python3 program to capitalise the first
# and last character of each word in a string.
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);
     
# Driver code
if __name__ == "__main__" :
     
    string = "Geeks for Geeks";
     
    print(string);
    print(FirstAndLast(string));
     
# This code is contributed by Ryuga


C#




// C# program to remove the first
// and last character of each word in a string.
using System;
 
class GFG
{
    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);
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String str = "Geeks for Geeks";
        Console.WriteLine(str);
        Console.WriteLine(FirstAndLast(str));
    }
}
 
/* This code contributed by PrinciRaj1992 */


PHP




<?php
// PHP program to capitalise the first
// and last character of each word in a string.
 
function FirstAndLast($str)
{
 
    // Create an equivalent string
    // of the given string
    $ch = $str;
    for ($i = 0; $i < strlen($ch); $i++)
    {
 
        // $k stores index of first character
        // and $i is going to store index of last
        // character.
        $k = $i;
        while ($i < strlen($ch) && $ch[$i] != ' ')
            $i++;
 
        // Check if the character is a small letter
        // If yes, then Capitalise
        $ch[$k] = chr(($ch[$k] >= 'a' && $ch[$k] <= 'z')
                    ? (ord($ch[$k]) - 32) : (ord($ch[$k])));
        $ch[$i - 1] = chr(($ch[$i - 1] >= 'a' && $ch[$i - 1] <= 'z' )
                    ? (ord($ch[$i - 1]) - 32) : (ord($ch[$i - 1])));
    }
 
    return $ch;
}
 
// Driver code
 
$str = "Geeks for Geeks";
echo $str, "\n";
echo FirstAndLast($str);
 
// This code is contributed by ihritik
 
?>


Javascript




<script>
 
// JavaScript program to capitalise the first
// and last character of each word in a string.
 
function FirstAndLast(str)
{
 
    // Create an equivalent string
    // of the given string
    var ch = str.split('');
    for (var i = 0; i < ch.length; i++)
    {
 
        // k stores index of first character
        // and i is going to store index of last
        // character.
        var k = i;
        while (i < ch.length && ch[i] != ' ')
            i++;
 
        // Check if the character is a small letter
        // If yes, then Capitalise
        ch[k] = String.fromCharCode(ch[k] >= 'a' &&
        ch[k] <= 'z' ? (ch[k].charCodeAt(0) - 32)
                     : ch[k].charCodeAt(0));
        ch[i - 1] = String.fromCharCode(ch[i - 1] >= 'a'
        && ch[i - 1] <= 'z'? (ch[i - 1].charCodeAt(0) - 32)
                            : ch[i - 1].charCodeAt(0));
    }
 
    return ch.join('');
}
 
// Driver code
 
var str = "Geeks for Geeks";
document.write( str + "<br>");
document.write( FirstAndLast(str));
 
 
</script>


Output: 

Geeks for Geeks
GeekS FoR GeekS

 

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

Auxiliary Space: O(N) where N is the length of the original string



Similar Reads

Java Program to Capitalize the First Letter of Each Word in a String
In Java Programming, we can be able to capitalize the first letter of each word in the given String value by using toUpperCase(), toLowerCase(), and another one is substring() method. These methods are available String class in Java and these methods are useful for our problem. In this article, we will learn how to capitalize the first letter of ea
5 min read
Print the first and last character of each word in a String
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 Run a loop from the first letter to the last letter.Print the first and last letter of the string.If there is a space in the string then print the character
7 min read
Remove the first and last character of each word in a string
Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if the character is the starting or end of the wordR
4 min read
Print last character of each word in a string
Given string str, the task is to print the last character of each word in the string.Examples: Input: str = "Geeks for Geeks" Output: s r s Input: str = "computer applications" Output: r s Approach: Append a space i.e. " " at the end of the given string so that the last word in the string is also followed by a space just like all the other words in
4 min read
Last remaining character after repeated removal of the first character and flipping of characters of a Binary String
Given a Binary string str of length N, the task is to find the last character removed from the string by repeatedly removing the first character of the string and flipping all the characters of the string if the removed character is '0'. Examples: Input: str = "1001" Output: '0' Explanation: Removing str[0] from the string modifies str to "001". Re
5 min read
Capitalize the First Letter of a String in Java Using Regex
In Java, we can use regular expressions to make the first character of each word in Uppercase as the word is represented as a String and string is the collection of characters. So, in Java, we can use pattern and matcher class methods to find the first character of a word and then replace it with its uppercase letter. In this article, we will discu
2 min read
Capitalize the First Letter of a String in Java
In Java, to check if a String contains only uppercase letters, we can use many approaches. These approaches verify each character in the String to ensure they are all in uppercase. A simple method, such as iterating through the characters and checking their case. In this article, we will discuss how to check if a String contains only uppercase lett
4 min read
Repeat last occurrence of each alphanumeric character to their position in character family times
Given a string str[] of size N, the task is to encode it in such a way that the last occurrence of each character occurs as long as its position in its family. As 'a' is the first character of its family (lower case alphabet), so it will remain 'a', but 'b' becomes 'bb', 'D' becomes 'DDDD' and so on. In case of numeric characters, the character occ
12 min read
Capitalize 1st character of all words having at least K characters
Given string str representing a sentence, and an integer K, the task is to capitalize all the words in the given sentence having at least K characters. Example: Input: str = "geeks for geeks", K = 4Output: Geeks for GeeksExplanation: The word "for" does not contain 4 characters, hence its 1st character is not capitalize. Input: str = "geeksforgeeks
5 min read
Modify string by increasing each character by its distance from the end of the word
Given a string S, the task is to modify the given string by replacing every character S[i] by a new character whose value is (S[i] + its position from the end of the word) Examples: Input: S = "acm fkz" Output: "cdm hlz" Explanation: There are 2 words in the given string {"acm", "fkz"} For "acm": a becomes 'a' + 2 = 'c' c becomes 'c' + 1 = 'd' m be
7 min read
How to find the first and last character of a string in Java
Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Last: a Explanation: The first character of given str
3 min read
Maximum product of first and last character of String after rotation
Given a string S of length N, the task is to find the maximum possible product of the first and the last character of the string if it is rotated any number of times toward left or right. Examples: Input: Str = "12345" Output: 20Explanation: If we rotate the string once in anticlockwise direction, then the string becomes 51234, and the product = 5*
4 min read
Remove the first and last occurrence of a given Character from a String
Given a character C and a string S, the task is to remove the first and last occurrence of the character C from the string S. Examples: Input: S = "GeekforGeeks", C = 'e' Output: GeksforGeks Explanation: GeekforGeeks -&gt; GekforGeks Input: S = "helloWorld", C = 'l' Output: heloWord Approach: The idea is to traverse the given string from both ends
9 min read
Swap the first and last character of a string in Java
Given string str, the task is to write a Java program to swap the first and the last character of the given string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: seeksForGeekGExplanation: The first character of the given string is 'G' and the last character of the given string is 's'. We swap the character 'G and 's' a
4 min read
Remove first and last character of a string in Java
Given string str, the task is to write Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: eeksForGeekExplanation: The first character of the given string is 'G' and the last character of the given string is 's'. After removing the first and last characte
7 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Kth character after replacing each character of String by its frequency exactly X times
Given a string S consisting of N digits from [1, 9] and a positive integer K and X. Every day each character of the string is replaced by its frequency and value. The task is to find the Kth character of the string after X days. Examples: Input: S = "1214", K = 10, X = 3Output: 4Explanation:1st day = "12214444"2nd day = “1222214444444444444444”3rd
8 min read
Count of substrings having the most frequent character in the string as first character
Given a string S consisting of lowercase alphabets of size N, the task is to count all substrings which contain the most frequent character in the string as the first character. Note: If more than one character has a maximum frequency, consider the lexicographically smallest among them. Examples: Input: S = "abcab"Output: 7Explanation:There are two
7 min read
Minimum operation require to make first and last character same
Given a string S. You are allowed two types of operations: Remove a character from the front of the string.Remove a character from the end of the string. The task is to find the minimum operations required to make the first and last character of the S same. In case, it is not possible, print "-1". Examples: Input : S = "bacdefghipalop" Output : 4 R
14 min read
Queries to find the last non-repeating character in the sub-string of a given string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}, {0, 12}} Output: G k r Sub-string for the querie
11 min read
Check if concatenation of first and last digits forms a prime number or not for each array element
Given an array Q[] consisting of N integers, the task for each element of the array Q[] is to check whether any of the numbers, formed by concatenating the first and the last digits of Q[i] is a prime number or not. Examples: Input: Q[] = {30, 66}Output: TrueFalseExplanation:Q[0]: Possible combinations are 3 and 30. Since 3 is a prime number, the o
9 min read
Most frequent word in first String which is not present in second String
Given two string 'S1' and 'S2', the task is to return the most frequent (which is used the maximum number of times) word from 'S1' that is not present in 'S2'. If more than one word is possible then print lexicographically smallest among them. Examples: Input: S1 = "geeks for geeks is best place to learn", S2 = "bad place" Output: geeks "geeks" is
7 min read
String containing first letter of every word in a given string with spaces
String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. Examples: Input : str = "geeks for geeks" Output : gfg Input : str = "geeks for geeks"" Output : hc Source: https://www.geeksforgeeks.
11 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string str and reversed string str are same. Input: str =
5 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Java Program to find the Last Index of a Particular Word in a String
To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found. Real-life Example: Consider an example of a book. The book contains pages where pages contain words. Now if a user wants to figure out the oc
4 min read
Remove last occurrence of a word from a given sentence string
Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is. Examples: Input: S = “This is GeeksForGeeks”, W="Geeks"Output: This is GeeksForExplanation:The last occurrence of “Geeks” in the string is substring over the range [16, 20]. Input: S=
11 min read
Length Of Last Word in a String
Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0. Examples: Input : str = "Geeks For Geeks"Output : 5length(Geeks)= 5Input : str = "Start Coding Here"Output : 4length(Here) = 4Input : **Output : 0Recommended PracticeL
14 min read
How to find the last index using regex of a particular word in a String?
To find the last index of a particular word in a string using regular expressions in Java, you can use the Matcher class along with a regular expression that captures the desired word. Java Program to last index Using the Regex of a Particular Word in a StringBelow is the implementation of the last index Using the Regex of a Particular Word in a St
2 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Practice Tags :