Program to short a string |C Program|

Introduction

     Shortening strings is a common task in programming, often used to create abbreviations or initials. In this blog post, we'll explore a simple C program that shortens a given string by extracting the initials of each word.  


Code

    
     
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>

    void main() {
        int i, j = 0, m = 0;
        char s[50], name[50];
    
        clrscr();
    
        // Input: User provides a string
        printf("Enter the string name: ");
        gets(s);
    
        // Extracting Initials
        for (i = 0; i <   strlen(s); i++) {
            name[m] = s[j];
    
            if (s[i] == ' ') {
                m = m + 1;
                j = i + 1;
                name[m] = s[j];
                j++;
            }
        }
    
        // Displaying Shortened Form
        printf("\nThe shortened form is\n");
        puts(name);
    
        getch();
    }
    
       
     


Output


        Enter the string name: computer science
        The shortened form is
        cs
       


    In this example, the user enters the string "computer science" The program extracts the initials of each word and displays the shortened form as "cs."

You can try running the program with different input strings to see how it accurately shortens them by extracting initials. The output will consist of the initials of each word in the given string.

Explanation

1. Header Files:
The program includes the standard input/output header <stdio.h>, the console input/output header <conio.h>, and the string manipulation header <string.h>.
2. Main Function:
3. Serves as the entry point of the program.
4. Input:
5. Users input a string, 's', which may contain multiple words.
6. Initial Extraction:
The program extracts the initials of each word from the input string and stores them in the 'name' array.
7. Output:
8. Displays the shortened form of the string, consisting of the extracted initials.


Conclusion

     This C program demonstrates a simple approach to shorten strings by extracting initials. It identifies spaces to determine the beginning of a new word and captures the initial letter of each word in the resulting abbreviation. Feel free to experiment with different input strings to observe how the program accurately shortens them by extracting initials. The program provides a useful tool for creating abbreviated forms of names or phrases in a concise manner. Happy coding!

Post a Comment

0 Comments