Open In App

C Program to Print the First Letter of Each Word

Last Updated : 20 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Here we will see how to build a C Program to Print the first letter of each word. Given a string, we have to find the first letter of each word.

Approach1:

  1. Traverse character array, for the first character, print it.
  2. Now for every character check whether its previous character is a whitespace character if yes then print it.

Input:

Geeks for Geeks

Output:

G f G

C




// C Program to demonstrate Printing
// of the first letter of each word
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[] = "GeeksforGeeks, A computer science portal "
                 "for geeks";
    int i, j = 0;
  
    // Traversing the Character array
    for (i = 0; i < strlen(str); i++) {
  
        // To store first character of
        // String if it is not a
        // whitespace.
        if (i == 0 && str[i] != ' ') {
            printf("%c ", str[i]);
        }
        // To check whether Character
        // is first character of
        // word and if yes store it.
        else if (i > 0 && str[i - 1] == ' ') {
            printf("%c ", str[i]);
        }
    }
    return 0;
}


Output

G A c s p f g 

Approach 2: Using strtok() Function

strtok() function is used to break the string into parts based on a delimiter, here delimiter is whitespace.

Syntax:

strtok(character array, char *delimiter);

C




// C Program to demonstrate Printing
// of the first letter
// of each word using strtok()
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[] = "GeeksforGeeks, A computer science portal for geeks";
    
    // This will give first word of String.
    char* ptr = strtok(str, " ");
    
    while (ptr != NULL) {
        
        // This will print first character of word.
        printf("%c ", ptr[0]);
        
        // To get next word.
        ptr = strtok(NULL, " ");
    }
}


Output

G A c s p f g 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads