简体   繁体   中英

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. 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...

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
  • if char read isn't alphanumeric, then it is written to the output file
  • else, the whole word is read with 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. If there would be longer words, reading with fscanf onto fixed-size buffer can be harmful.

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.

  • 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. 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.

  • Your for loop is checking each pair of letters twice. i only needs to scan over half of the word length.

  • You only need a single if within palindrome() . I'm not sure why you have so many. They're redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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