C program to print all words in a string ends with a specific character

C program to print all words in a string ends with a specific character:

In this post, we will learn how to print all words in a string those are ending with a specific character in C. For example, for the language one two three four, we have one and three ends with e.

The string and the character is given, we just need to print all the words those are ending with that character.

Algorithm:

We will follow the below algorithm to solve it:

  • Iterate through the characters of the string one by one. Keep one head pointer variable to point to the start character of the current word.
  • While iterating through the characters, if it finds any blank space, it will check if the previous character is equal to the given character or not. If it is equal, print the current word using the head pointer.
  • If it finds a blank space and the previous character is not equal to the given character, then just update the head pointer.

C program to print words ends with a character:

Let’s take a look at the below program:

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

int main()
{
    char str[] = "One two three four";
    char ch = 'r';
    int i = 0, j = 0, head = 0, len;

    len = strlen(str);

    str[len] = ' ';

    for (i = 0; i < len + 1; i++)
    {
        if (str[i] == ' ' && str[i - 1] == ch)
        {
            while (head < i)
            {
                printf("%c", str[head]);
                head++;
            }
            printf("\n");
            head = i + 1;
        }
        else
        {
            if (str[i] == ' ')
            {
                head = i + 1;
            }
        }
    }
}

Here,

  • str is the given string and ch is the given character.
  • head is used to point to the current word index.
  • len is holding the string length.
  • We are changing the last character to blank character because the loop below checks for a blank and its previous character. This will help us to detect the last word in the string.
  • The for loop is used to iterate through the characters of the string one by one.
  • It checks if the current character is blank and the previous character is equal to the given character. If yes, it prints the word by using the head pointer. It also updates the head to point to the first character index of the next word.
  • If the previous character is not equal to the given character and current character is not blank, it checks if only current character is blank or not, if yes, it updates the value of head to point to the next word.

If you run this program, it will print the below output:

four

You can also try this program by changing the string and the character values.

You might also like: