C Program to Print the First Letter of Each Word
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:
- Traverse character array, for the first character, print it.
- Now for every character check whether its previous character is a whitespace character if yes then print it.
Input:
Beginner for Beginner
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[] = "w3wiki, A computer science portal " "for Beginner" ; 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[] = "w3wiki, A computer science portal for Beginner" ; // 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
Contact Us