Dremendo Tag Line

Input a sentence and print those words which begins and ends with same alphabet in C++

String Methods - Question 6

In this question, we will see how to input a sentence and print those words which begins and ends with same alphabet in C++ programming. To know more about string methods click on the string methods lesson.

Q6) Write a program in C++ to input a sentence and print those words which begins and ends with same alphabet.

Program

#include <iostream>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>

using namespace std;

int main()
{
    char s[100],w[30];
    char fc,lc;
    int i,p=0;

    cout<<"Enter a sentence\n";
    gets(s);
    strcat(s," ");

    for(i=0; i<strlen(s); i++)
    {
        if(s[i]!=' ')
        {
            // store the characters in array w until we find a space
            w[p]=s[i];
            p++;
        }
        else
        {
            // terminate the word by a null character
            w[p]='\0';

            // first character
            fc=tolower(w[0]);

            // last character
            lc=tolower(w[strlen(w)-1]);

            if(fc==lc)
            {
                cout<<w<<endl;
            }
            p=0;
        }
    }
    return 0;
}

Output

Enter a sentence
My mom and dad love me so much
mom
dad
video-poster