C# - How to print the abbreviation of a string?

Given a string, we have to print the abbreviation of the given string using C# program?
Submitted by Nidhi, on October 12, 2020 [Last updated : March 21, 2023]

Here, we will find the abbreviation of a given string, for example, the abbreviation of string "information technology" is "I.T." that will be printed on the console screen.

C# program to print the abbreviation of a given string

The source code to print the abbreviation of a given string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - How to print the abbreviation of a string?.

using System;

class Sample
{
    public static string GetAbbreviation(string str)
    {
        char[] tempArray = new char[str.Length];
        string abbr="";
        int loop = 0;
        
        
        tempArray = str.ToCharArray();

        abbr += (char)((int)tempArray[0] ^ 32);
        abbr += '.';

        for (loop = 0; loop < str.Length - 1; loop++)
        {
            if (tempArray[loop] == ' ' || tempArray[loop] == '\t' || tempArray[loop] == '\n')
            {

                abbr += (char)((int)tempArray[loop + 1] ^ 32);
                abbr += '.';
            }
        }

        return abbr;
    }
    public static void Main()
    {
        string str = "information technology";
        string abr = "";

        abr = GetAbbreviation(str);

        Console.WriteLine("Abbreviation: " + abr);
    }
}

Output

Abbreviation: I.T.
Press any key to continue . . .

Explanation

Here, we created a class Sample that contains two static methods GetAbbreviation() and Main().

The GetAbbreviation() method is used to get the abbreviation of a given string. The abbreviation is used to represent the first character of every word in the specified string.

In the Main() method, we created a string str, which is initialized with "information technology" then we get the abbreviation using GetAbbreviation() method, and print the result on the screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.