简体   繁体   English

C语言回文

[英]Word palindrome in C

My task is to find word palindromes in a text file and to NOT print them into results file. 我的任务是在文本文件中找到单词回文,而不是将它们打印到结果文件中。 The results file should only contain all the spaces and words that are NOT palindromes. 结果文件应仅包含不是回文的所有空格和单词。 I've been working on this program for two solid weeks, but as I am a total newb in C, I can't simply imagine how to do this correctly. 我已经在这个程序上工作了两个星期,但是由于我是C语言的新手,所以我无法简单地想象如何正确地做到这一点。 Also, I have to work in Linux environent, so I can't use commands like strrev() which would make my life a lot easier at this point... 另外,我必须在Linux环境中工作,所以我不能使用诸如strrev()之类的命令,这将使我的生活更加轻松...

Anyways, data file contains a lot of words in a lot of lines separated by quite a few spaces. 无论如何,数据文件在很多行中包含很多单词,这些单词之间用空格隔开。

Here is the program that is working, but doesn't work with any spaces, because I don't know how to check them at the needed place. 这是正在运行的程序,但不适用于任何空格,因为我不知道如何在所需位置检查它们。

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

const int CMAX  = 1000;
const int Dydis = 256;
FILE *dataFile;
FILE *resFile;

void palindrome(char *linex);

int main(){
    char duom[CMAX], res[CMAX], linex[Dydis];

    printf("What's the name of data file? \n");
    scanf("%s", duom);
    dataFile=fopen(duom, "r");
    if (dataFile==NULL){
        printf ("Error opening data file \n");
        return 0;
    };

    printf("What's the name of results file? \n");
    scanf ("%s", res);
    resFile=fopen(res, "w");
    if (resFile==NULL){
        printf ("Error opening results file \n");
        return 0;
    };

    while (fgets(linex, sizeof(linex), dataFile)) {
        palindrome(linex);
    }
    printf ("all done!");
    fclose(dataFile);
    fclose(resFile);
}

void palindrome(char *linex){
    int i, wordlenght, j;
    j = 0;
    char *wordie;
    const char space[2] = " ";
    wordie = strtok(linex, space);
    while ( wordie != NULL ) {
        wordlenght = strlen(wordie);
        if (wordie[j] == wordie[wordlenght-1]) {
            for (i = 0; i < strlen(wordie); i++) {
                if (wordie[i] == wordie[wordlenght-1]) {
                    if (i == strlen(wordie)-1) {
                        fprintf(resFile,"");
                    }
                    wordlenght--;
                }
                else {
                    fprintf(resFile,"%s", wordie);
                    break;
                }
            }
        }
        else {
            fprintf(resFile,"%s", wordie);
        }

        wordie = strtok(NULL, space);
    }
}

EDIT: 编辑:

Code below works as following: 下面的代码如下所示:

  • input file is read char by char 输入文件由char读取char
  • if char read isn't alphanumeric, then it is written to the output file 如果char读取的不是字母数字,则将其写入输出文件
  • else, the whole word is read with fscanf 否则,用fscanf读取整个单词
  • if word is not a palindrome, then write to the output file 如果单词不是回文,则写入输出文件


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

int is_pal(char* word) {
    size_t len = strlen(word);
    char* begin = word;
    char* end = word + len - 1;
    if (len == 1) {
        return 1;
    }
    while (begin <= end) {
        if (*begin != *end) {
            return 0;
        }
        begin++;
        end--;
    }
    return 1;
}

int main(void)
{
    FILE* fin = fopen("pals.txt", "r");
    if (fin == NULL) {
        perror("fopen");
        exit(1);
    }
    FILE* fout = fopen("out_pals.txt", "w");
    if (fout == NULL) {
        perror("fopen");
        exit(1);
    }
    int ret;
    char word[100];
    while ((ret = fgetc(fin)) != EOF) {
        if (!isalpha(ret)) {
            fprintf(fout, "%c", ret);
        }
        else {
            ungetc(ret, fin);
            fscanf(fin, "%s", word);
            if (!is_pal(word)) {
                fprintf(fout, "%s", word);
            }
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}

I've created file with following content: 我创建了具有以下内容的文件:

cancer kajak anna sam truck
test1   abc   abdcgf  groove   void
xyz annabelle  ponton  belowoleb   thing
cooc  ringnir

The output file : 输出文件:

cancer   sam truck
test1   abc   abdcgf  groove   void
xyz annabelle  ponton     thing
(line with two spaces)

As you can see, the number of spaces between words are the same as in the input file. 如您所见,单词之间的空格数与输入文件中的空格数相同。

I've assumed that single word could have 100 chars maximum. 我假设单个单词最多可以包含100个字符。 If there would be longer words, reading with fscanf onto fixed-size buffer can be harmful. 如果会有更长的单词,用fscanf读取固定大小的缓冲区可能会很有害。

Hints: 提示:

  • strtok() gives you a pointer to the start of delimited words but it does not extract them or put them in their own string for you. strtok()为您提供了一个指向分隔词开头的指针,但不会提取它们或将它们放在自己的字符串中。

  • You need some logic to find the end of each word. 您需要一些逻辑来找到每个单词的结尾。 The function strlen() will tell you how many characters there are from the char* that it gets until a null-character. 函数strlen()会告诉您从char *直到空字符为止有多少个字符。 If you give it a pointer to the start of a word within a sentence it will give you the length from the start of the word to the end of the sentence. 如果您给它一个指向句子中单词开头的指针,它将为您提供从单词开头到句子结尾的长度。

  • Breaking palindrome() into a function that loops over words in a line and a function that returns whether or not a single word is a palindrome may help. palindrome()分解为在一行中循环单词的函数,并返回一个单词是否是回文词的函数可能会有所帮助。

  • Your for loop is checking each pair of letters twice. 您的for循环将检查每对字母两次。 i only needs to scan over half of the word length. i只需要扫描一半以上的字长。

  • You only need a single if within palindrome() . ifpalindrome()内,则只需要一个。 I'm not sure why you have so many. 我不确定你为什么这么多。 They're redundant. 他们是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM