Open In App

Print the first and last character of each word in a String

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// CPP program to print
// the first and last character
// of each word in a String
#include<bits/stdc++.h>
using namespace std;
 
// Function to print the first
// and last character of each word.
void FirstAndLast(string str)
{
    int i;
 
    for (i = 0; i < str.length(); i++)
    {
        // If it is the first word
        // of the string then print it.
        if (i == 0)
            cout<<str[i];
 
        // If it is the last word of the string
        // then also print it.
        if (i == str.length() - 1)
            cout<<str[i];
 
        // If there is a space
        // print the successor and predecessor
        // to space.
        if (str[i] == ' ')
        {
            cout<<str[i-1]<<" "<<str[i+1];
        }
    }
}
 
// Driver code
int main()
{
    string str = "Geeks for Geeks";
    FirstAndLast(str);
}
     
// This code is contributed by
// Surendra_Gangwar


Java




// Java program to print
// the first and last character
// of each word in a String
 
class GFG {
 
    // Function to print the first
    // and last character of each word.
    static void FirstAndLast(String str)
    {
        int i;
 
        for (i = 0; i < str.length(); i++) {
 
            // If it is the first word
            // of the string then print it.
            if (i == 0)
                System.out.print(str.charAt(i));
 
            // If it is the last word of the string
            // then also print it.
            if (i == str.length() - 1)
                System.out.print(str.charAt(i));
 
            // If there is a space
            // print the successor and predecessor
            // to space.
            if (str.charAt(i) == ' ') {
                System.out.print(str.charAt(i - 1)
                                 + " "
                                 + str.charAt(i + 1));
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str = "Geeks for Geeks";
        FirstAndLast(str);
    }
}


Python3




# Python3 program to print
# the first and last character
# of each word in a String'
 
# Function to print the first
# and last character of each word.
def FirstAndLast(string):
    for i in range(len(string)):
 
        # If it is the first word
        # of the string then print it.
        if i == 0:
            print(string[i], end = "")
 
        # If it is the last word of the string
        # then also print it.
        if i == len(string) - 1:
            print(string[i], end = "")
 
        # If there is a space
        # print the successor and predecessor
        # to space.
        if string[i] == " ":
            print(string[i - 1],
                  string[i + 1], end = "")
 
# Driver code
if __name__ == "__main__":
    string = "Geeks for Geeks"
    FirstAndLast(string)
 
# This code is contributed by
# sanjeev2552


C#




// C# program to print
// the first and last character
// of each word in a String
using System;
 
class GFG
{
 
    // Function to print the first
    // and last character of each word.
    static void FirstAndLast(string str)
    {
        int i;
 
        for (i = 0; i < str.Length; i++)
        {
 
            // If it is the first word
            // of the string then print it.
            if (i == 0)
                Console.Write(str[i]);
 
            // If it is the last word of the string
            // then also print it.
            if (i == str.Length - 1)
                Console.Write(str[i]);
 
            // If there is a space
            // print the successor and predecessor
            // to space.
            if (str[i] == ' ')
            {
                Console.Write(str[i - 1]
                                + " "
                                + str[i + 1]);
            }
        }
    }
 
    // Driver code
    public static void Main()
    {
        string str = "Geeks for Geeks";
        FirstAndLast(str);
    }
}
 
// This code is contributed by Ryuga


Javascript




<script>
 
      // JavaScript program to print
      // the first and last character
      // of each word in a String'
       
      // Function to print the first
      // and last character of each word.
      function FirstAndLast(str)
      {
        for (var i = 0; i < str.length; i++)
        {
          // If it is the first word
          // of the string then print it.
          if (i == 0)
          document.write(str[i]);
 
          // If it is the last word of the string
          // then also print it.
          if (i == str.length - 1)
          document.write(str[i]);
 
          // If there is a space
          // print the successor and predecessor
          // to space.
          if (str[i] === " ") {
            document.write(str[i - 1] + " " + str[i + 1]);
          }
        }
      }
 
      // Driver code
      var str = "Geeks for Geeks";
      FirstAndLast(str);
       
 </script>


Output

Gs fr Gs

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++




// CPP program to print
// the first and last character
// of each word in a String
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the first
// and last character of each word.
void FirstAndLast(string str)
{
    // Split the string into words using stringstream
    stringstream ss(str);
    string word;
    while (ss >> word) {
        // Print the first and last character of the word
        cout << word[0] << word[word.length() - 1] << " ";
    }
}
 
// Driver code
int main()
{
    string str = "Geeks for Geeks";
    FirstAndLast(str);
}


Java




// Java program to print
// the first and last character
// of each word in a String
import java.util.*;
 
class Main {
     
    // Function to print the first and last character of each word.
    public static void firstAndLast(String str) {
        // Split the string into words using StringTokenizer
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreTokens()) {
            String word = st.nextToken();
            // Print the first and last character of the word
            System.out.print(word.charAt(0) + "" + word.charAt(word.length() - 1) + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        String str = "Geeks for Geeks";
        firstAndLast(str);
    }
}


Python3




# Python program to print the first
# and last character of each word
# in a string.
 
# Function to print the first and last
# character of each word
def FirstAndLast(string):
    # Split the string into words using split()
    words = string.split()
    for word in words:
        # Print the first and last character of the word
        print(word[0] + word[-1], end=" ")
 
# Driver code
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)
    {
        // Split the string into words using Linq
        List<string> words = str.Split(' ').ToList();
 
        // Print the first and last character of each word
        foreach(string word in words)
        {
            Console.Write(word[0]);
            Console.Write(word[word.Length - 1]);
            Console.Write(" ");
        }
    }
}


Javascript




// JAVASCRIPT program to print
// the first and last character
// of each word in a String
 
// Function to print the first
// and last character of each word.
function FirstAndLast(str) {
    // Split the string into words using split()
    let words = str.split(" ");
    let output = "";
    for (let i = 0; i < words.length; i++) {
        // Print the first and last character of the word
        output += words[i][0] + words[i][words[i].length - 1] + " ";
    }
    console.log(output);
}
 
// Driver code
let str = "Geeks for Geeks";
FirstAndLast(str);


Output

Gs fr Gs 

Time Complexity: O(N)

Space Complexity: O(1)



Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads