C Program to Print the First Letter of Each Word
Last Updated :
20 Jul, 2022
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:
Geeks for Geeks
Output:
G f G
C
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "GeeksforGeeks, A computer science portal "
"for geeks" ;
int i, j = 0;
for (i = 0; i < strlen (str); i++) {
if (i == 0 && str[i] != ' ' ) {
printf ( "%c " , str[i]);
}
else if (i > 0 && str[i - 1] == ' ' ) {
printf ( "%c " , str[i]);
}
}
return 0;
}
|
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
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "GeeksforGeeks, A computer science portal for geeks" ;
char * ptr = strtok (str, " " );
while (ptr != NULL) {
printf ( "%c " , ptr[0]);
ptr = strtok (NULL, " " );
}
}
|
Share your thoughts in the comments
Please Login to comment...