Home > Software engineering >  Find a palindrome words in a string and then rewrite them, in C
Find a palindrome words in a string and then rewrite them, in C

Time:11-30

Hi, how can i write a code in C that checks a string for palindromes, and then rewrites them? For example: string> "awbiue abdba aebto leoel", should return "abdba leoel".

I wrote this code, but it can only find that the string is palindrome or not:

#include<stdlib.h>
#include<string.h>

int main()
{
char str[100];

printf("Enter string: ");
gets(str);
 int f=1;

{

for(int i=0;i<strlen(str); i  )
{
    if(str[i]!=str[strlen(str)-i-1])
    {
        f=0;  break;
    }
}
if(f==1)
    printf("Palindrom");
else
    printf("Not Palindrom");}
return 0;
}

CodePudding user response:

You only need to read string by string, making sure whether they are palindrome, and if so, print them out -- that is what I did in the following code:

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

int main()
{
    char str[100];
    printf("Enter string: ");
    while(scanf("%s", str) == 1) { // read strings one by one in the str variable
        //your code part
        int f=1;

        for(int i=0;i<strlen(str); i  )
        {
            if(str[i]!=str[strlen(str)-i-1])
            {
                f=0;  break;
            }
        }
        if(f==1) // that means that string is palindrome
            printf("%s ", str); // print the string and a space

    }
    return 0;
}
  • Related