【问题标题】:Find a palindrome words in a string and then rewrite them, in C在字符串中找到一个回文词,然后用 C 重写它们
【发布时间】:2021-11-29 17:14:40
【问题描述】:

您好,我如何在 C 中编写代码来检查字符串中的回文,然后重写它们? 例如:string>“awbiue abdba aebto leoel”,应该返回“abdba leoel”。

我写了这段代码,但它只能找到字符串是否是回文:

#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;
}

【问题讨论】:

标签: c palindrome


【解决方案1】:

您只需要逐个字符串读取,确定它们是否是回文,如果是,则将它们打印出来——这就是我在以下代码中所做的:

#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;
}

【讨论】:

  • 请注意,scanf("%s", pointer) 从输入中读取一个以空格分隔的字符序列到该指针中,并使用终止空字符将其写入,正如strlen 所期望的那样。另请注意,scanf 通常不会处理任何内容,直到按下 enter 键刷新输入。
  • 哟,谢谢!你帮了很多忙。
猜你喜欢
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
相关资源
最近更新 更多