Open In App

Program to print the initials of a name with the surname

Last Updated : 23 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a full name in the form of a string, the task is to print the initials of a name, in short, and the surname in full. 

Examples:

Input: Devashish Kumar Gupta
Output: D. K. Gupta
Input: Ishita Bhuiya
Output: I. Bhuiya

Approach: The basic approach is to extract words one by one and then print the first letter of the word, followed by a dot(.). For the surname, extract and print the whole word. Below is the implementation of the above approach: 

C++
// C++ program to print the initials
// of a name with the surname
#include <bits/stdc++.h>
using namespace std;

void printInitials(string str) 
{
    int len = str.length();

    // to remove any leading or trailing spaces
    str.erase(0, str.find_first_not_of(' '));
    str.erase(str.find_last_not_of(' ') + 1);

    // to store extracted words
    string t = "";
    for (int i = 0; i < len; i++) 
    {
        char ch = str[i];

        if (ch != ' ')

            // forming the word
            t = t + ch;

        // when space is encountered
        // it means the name is completed
        // and thereby extracted
        else
        {
            // printing the first letter
            // of the name in capital letters
            cout << (char)toupper(t[0]) << ". ";
            t = "";
        }
    }

    string temp = "";

    // for the surname, we have to print the entire
    // surname and not just the initial
    // string "t" has the surname now
    for (int j = 0; j < t.length(); j++) 
    {
        // first letter of surname in capital letter
        if (j == 0) temp = temp + (char)toupper(t[0]);

        // rest of the letters in small
        else
            temp = temp + (char)tolower(t[j]);
    }

    // printing surname
    cout << temp << endl;
}

// Driver Code
int main() 
{
    string str = "ishita bhuiya";
    printInitials(str);
}

// This code is contributed by
// sanjeev2552
Java
// Java program to print the initials
// of a name with the surname
import java.util.*;

class Initials {
    public static void printInitials(String str)
    {
        int len = str.length();

        // to remove any leading or trailing spaces
        str = str.trim();

        // to store extracted words
        String t = "";
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);

            if (ch != ' ') {

                // forming the word
                t = t + ch;
            }

            // when space is encountered
            // it means the name is completed
            // and thereby extracted
            else {
                // printing the first letter
                // of the name in capital letters
                System.out.print(Character.toUpperCase(t.charAt(0))
                                 + ". ");
                t = "";
            }
        }

        String temp = "";

        // for the surname, we have to print the entire
        // surname and not just the initial
        // string "t" has the surname now
        for (int j = 0; j < t.length(); j++) {

            // first letter of surname in capital letter
            if (j == 0)
                temp = temp + Character.toUpperCase(t.charAt(0));

            // rest of the letters in small
            else
                temp = temp + Character.toLowerCase(t.charAt(j));
        }

        // printing surname
        System.out.println(temp);
    }

    public static void main(String[] args)
    {
        String str = "ishita bhuiya";
        printInitials(str);
    }
}
Python3
# Python program to print the initials
# of a name with the surname
def printInitials(string: str):
    length = len(string)

    # to remove any leading or trailing spaces
    string.strip()

    # to store extracted words
    t = ""
    for i in range(length):
        ch = string[i]
        if ch != ' ':

            # forming the word
            t += ch

        # when space is encountered
        # it means the name is completed
        # and thereby extracted
        else:

            # printing the first letter
            # of the name in capital letters
            print(t[0].upper() + ". ", end="")
            t = ""

    temp = ""

    # for the surname, we have to print the entire
    # surname and not just the initial
    # string "t" has the surname now
    for j in range(len(t)):

        # first letter of surname in capital letter
        if j == 0:
            temp += t[0].upper()

        # rest of the letters in small
        else:
            temp += t[j].lower()

    # printing surname
    print(temp)

# Driver Code
if __name__ == "__main__":

    string = "ishita bhuiya"
    printInitials(string)

# This code is contributed by
# sanjeev2552
C#
// C# program to print the initials 
// of a name with the surname 
using System;

class Initials { 
    
    public static void printInitials(string str) 
    { 
        int len = str.Length ;

        // to remove any leading or trailing spaces 
        str = str.Trim(); 

        // to store extracted words 
        String t = ""; 
        for (int i = 0; i < len; i++) { 
            char ch = str[i]; 

            if (ch != ' ') { 

                // forming the word 
                t = t + ch; 
            } 

            // when space is encountered 
            // it means the name is completed 
            // and thereby extracted 
            else { 
                // printing the first letter 
                // of the name in capital letters 
                Console.Write(Char.ToUpper(t[0]) 
                                + ". "); 
                t = ""; 
            } 
        } 

        string temp = ""; 

        // for the surname, we have to print the entire 
        // surname and not just the initial 
        // string "t" has the surname now 
        for (int j = 0; j < t.Length; j++) { 

            // first letter of surname in capital letter 
            if (j == 0) 
                temp = temp + Char.ToUpper(t[0]); 

            // rest of the letters in small 
            else
                temp = temp + Char.ToLower(t[j]); 
        } 

        // printing surname 
        Console.WriteLine(temp); 
    } 

    public static void Main() 
    { 
        string str = "ishita bhuiya"; 
        printInitials(str); 
    } 
    // This code is contributed by Ryuga
} 
JavaScript
<script>

// JavaScript program to print the initials
// of a name with the surname
function printInitials(string){
    let Length = string.length

    // to remove any leading or trailing spaces
    string = string.trim()

    // to store extracted words
    let t = ""
    for(let i=0;i<Length;i++){
        let ch = string[i]
        if(ch != ' ')

            // forming the word
            t += ch

        // when space is encountered
        // it means the name is completed
        // and thereby extracted
        else{

            // printing the first letter
            // of the name in capital letters
            document.write(t[0].toUpperCase() + ". ","")
            t = ""
        }
    }

    let temp = ""

    // for the surname, we have to print the entire
    // surname and not just the initial
    // string "t" has the surname now
    for(let j=0;j<t.length;j++){

        // first letter of surname in capital letter
        if(j == 0)
            temp += t[0].toUpperCase()

        // rest of the letters in small
        else
            temp += t[j].toLowerCase()
    }

    // printing surname
    document.write(temp,"</br>")
}

// Driver Code

let string = "ishita bhuiya"
printInitials(string)


// this code is contributed by shinjanpatra

</script>

Output
I. Bhuiya

Time complexity: O(n), Here n is the length of the string.
Auxiliary space: O(1), As constant extra space is used.

Approach:

  • Split the name using the space delimiter.
  • Get the first character of each name part and append a period to it.
  • Combine the initials and the last name using a space.
  • Print the result.
C++
#include <iostream>
#include <string>
#include <vector>

int main() {
  // take input from the user
  std::string name = "Uppala Omkhar";

  // split the name into parts
  std::vector<std::string> name_parts;
  std::string part;
  for (char c : name) {
    if (c == ' ') {
      name_parts.push_back(part);
      part = "";
    } else {
      part += c;
    }
  }
  name_parts.push_back(part);

  // get the initials and surname
  std::string initials = "";
  for (int i = 0; i < name_parts.size() - 1; i++) {
    initials += toupper(name_parts[i][0]);
    initials += ". ";
  }

  std::string surname = name_parts.back();
  surname[0] = toupper(surname[0]);

  // print the result
  std::cout << initials << surname << std::endl;

  return 0;
}
Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // take input from the user
        String name = "Uppala Omkhar";

        // split the name into parts
        String[] nameParts = name.split(" ");
        ArrayList<String> namePartsList = new ArrayList<>();
        for (String part : nameParts) {
            namePartsList.add(part);
        }

        // get the initials and surname
        StringBuilder initials = new StringBuilder();
        for (int i = 0; i < namePartsList.size() - 1; i++) {
            initials.append(Character.toUpperCase(namePartsList.get(i).charAt(0))).append(". ");
        }

        String surname = namePartsList.get(namePartsList.size() - 1);
        surname = Character.toUpperCase(surname.charAt(0)) + surname.substring(1);

        // print the result
        System.out.println(initials.toString() + surname);
    }
}
Python3
# take input from the user
name = "Uppala Omkhar"

# split the name into parts
name_parts = name.split()

# get the initials and surname
initials = ""
for part in name_parts[:-1]:
    initials += part[0].upper() + ". "

surname = name_parts[-1].capitalize()

# print the result
print(initials + surname)
C#
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Take input from the user
        string name = "Uppala Omkhar";

        // Split the name into parts
        List<string> nameParts = new List<string>();
        string part = "";
        foreach (char c in name)
        {
            if (c == ' ')
            {
                nameParts.Add(part);
                part = "";
            }
            else
            {
                part += c;
            }
        }
        nameParts.Add(part);

        // Get the initials and surname
        string initials = "";
        for (int i = 0; i < nameParts.Count - 1; i++)
        {
            initials += char.ToUpper(nameParts[i][0]) + ". ";
        }

        string surname = nameParts[nameParts.Count - 1];
        surname = char.ToUpper(surname[0]) + surname.Substring(1);

        // Print the result
        Console.WriteLine(initials + surname);
    }
}
JavaScript
// take input from the user
const name = "Uppala Omkhar";

// split the name into parts
const nameParts = [];
let part = "";
for (const char of name) {
    if (char === ' ') {
        nameParts.push(part);
        part = "";
    } else {
        part += char;
    }
}
nameParts.push(part);

// get the initials and surname
let initials = "";
for (let i = 0; i < nameParts.length - 1; i++) {
    initials += nameParts[i][0].toUpperCase() + ". ";
}

let surname = nameParts[nameParts.length - 1];
surname = surname[0].toUpperCase() + surname.slice(1);

// print the result
console.log(initials + surname);

Output
U. Omkhar

Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), as we are not using any extra data structure.


Next Article
Practice Tags :

Similar Reads