In a string that contains multiple words, each word is separated by a whitespace. In this article, we will learn how to print the first letter of each word using a C program.
The simplest method to print the first letter of each word is by using a loop. Let’s take a look at an example:
#include <stdio.h>
#include <string.h>
void print(char *s) {
// Flag to check if it's first letter of a word
int first = 1;
// Loop through string character by character
for (int i = 0; s[i] != '\0'; i++) {
// Check if the current character is a non-space
// and the start of a word
if (s[i] != ' ' && first) {
printf("%c ", s[i]);
first = 0;
}
// If a space is encountered, set the flag to 1
if (s[i] == ' ')
first = 1;
}
}
int main() {
char s[] = "Hello Geeks. Welcome to C programming";
// Printing first character of each word in s
print(s);
return 0;
}
Output
H G W t C p
Explanation: We traverse the string, and every time we find a non-space character that follows a space (or is at the start of the string), we print that character.
There are also a few other methods in C to print the first letter of each word. They are as follows:
Using strtok()
Another approach is to use the strtok() function, which breaks a string into tokens based on delimiters. We can use space ' ' as the delimiter to extract each word from the string and print the first character of each word.
#include <stdio.h>
#include <string.h>
void print(char *s) {
// Tokenize the string based on spaces
char *word = strtok(s, " ");
// Tokenize all words and print first letter
while (word != NULL) {
printf("%c ", word[0]);
word = strtok(NULL, " ");
}
}
int main() {
char s[] = "Hello Geeks. Welcome to C programming";
// Printing first character of each word in s
print(s);
return 0;
}
Output
H G W t C p
Using sscanf()
We can also use sscanf() to read individual words from the string, one by one, and print the first letter of each word. This approach works by scanning each word and extracting the first character.
#include <stdio.h>
void print(char *s) {
char word[100];
// Extracting words using sscanf
while (sscanf(s, "%s", word) == 1) {
// Print the first letter of the word
printf("%c ", word[0]);
// Move the pointer to the next word
s = s + strlen(word);
// Skip any leading spaces
while (*s == ' ') s++;
}
}
int main() {
char s[] = "Hello Geeks. Welcome to C programming";
// Printing first character of each word in s
print(s);
return 0;
}
Output
H G W t C p