回文字符串

问题描述 投票:0回答:1

测试字符串是否为回文的代码。该字符串可以包含任意数量的空格、标点符号 (. ? !,),区分大小写。该代码适用于女士、赛车、雷达等字符串。但是,对一个计划巴拿马运河的人、一个计划巴拿马运河、雪茄的人来说,不会有用吗?把它扔进罐子里,太惨了

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

int main(){
    char string[100];
    printf("Enter a string: ");
    scanf("%[^\n]", string);

    int isPalindrome = 1;  // assign 0 to this if the string is a NOT palindrome

    // code to test if string is a palindrome
    char str1[100], str2[100];
    int len = strlen(string)-1;
    int i;

    for (i = 0; i <= len; i++) {
        if (string[i] == '?' || string[i] == '.' || string[i] == '!' || string[i] == ',' || string[i] == '    ') {
            i++; 
        }

        strcpy(str1, string);
    }

    int length = strlen(str1)-1;
    int j, k;

    for (j = length; j >= 0; j--) {
        str2[j] = str1[len-j]; 
    }

    k = strcmp(str2, str1);

    // at the end you need to test
    if (k == 0) {
        printf("Yes, it is Palindrome!\n");
    }
    else {
        printf("No, not a Palindrome\n");
    }

    return 0;
}
c c-strings
1个回答
0
投票

您需要清理输入字符串以删除所有非字母字符。您的代码看起来对此很迷茫,但这是一个简单的任务。

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

char *clean_string(const char *str) {
    size_t len = strlen(str);
    char *new_string = calloc(len + 1, 1);

    // Error check `calloc`

    size_t i, j;
    for (i = 0, j = 0; i < len; i++) {
        if (isalpha(str[i])) 
            new_string[j++] = tolower(str[i]);
    }

    new_string[j] = '\0';
    return new_string;
}

如果我们测试一下:

int main(void) {
    char *s = clean_string("a man a plan a CAnal");
    printf("%s\n", s);
    free(s);
}

我们看到:

amanaplanacanal

解决了这个问题后,你的回文逻辑现在应该更容易了。所有编程问题都是当你将它们分解为更小的问题时出现的。

© www.soinside.com 2019 - 2024. All rights reserved.