简体   繁体   English

C。 使用 3 个函数确定字符串是否为回文

[英]C. decide if string is a palindrome using 3 functions

I'm supposed to make a code that determines if entered string is a palindrome, the code is supposed to have 3 functions.我应该编写一个代码来确定输入的字符串是否是回文,该代码应该有 3 个函数。 the first is to determine if sting is palindrome, the second is to use isalpha() to remove all non letters and the third is to use tolower to remove the difference between upper and lower case letters.第一个是判断 sting 是否是回文,第二个是使用 isalpha() 删除所有非字母,第三个是使用 tolower 删除大小写字母之间的差异。 I made all 3 separate functions but now that I have to combine them the code just gives exception thrown.我制作了所有 3 个单独的函数,但现在我必须将它们组合起来,代码只会抛出异常。

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

int isPalindrome(char inputString[])
{
    int middle = strlen(inputString) / 2;
    int len = strlen(inputString);
    for (int i = 0; i < middle; i++)
        if (inputString[i] != inputString[len - i - 1])
        {
            return 0;
        }
        else
        {
            return 1;
        }
}

void checker(char stringWithoutSpace[], char bigArray[]) 
{
    int j = 0;
    for (int i = 0; i < strlen(stringWithoutSpace); i++)
    {
        if (isalpha(stringWithoutSpace[i]) != 0)
        {
            bigArray[j++] = stringWithoutSpace[i];
        }
    }
} 

void lowerCase(char* string)
{
    int i;
    for (i = 0; string[i]; i++) 
    {
        string[i] = tolower(string[i]);
    }
}

#define SIZE 1000

int main(void) {
    int repeat = 1;
    char arrayPalindrome[SIZE];
    char bigArray[SIZE];
  
    while (repeat == 1)
    {   
        printf("Enter a sentence: ");
        scanf_s("%s", &arrayPalindrome);

        checker(arrayPalindrome, bigArray);
        lowerCase(arrayPalindrome, bigArray);

        if (isPalindrome(arrayPalindrome) == 1) 
        {
            printf("This is a palindrome.");
        }
        else
        {
            printf("this in not a palindrome: ");
        }
        printf("Do you want to enter another sentence (0 for no, 1 for yes)?");
        scanf_s("%d", &repeat);
    }

    return 0;
}

For starters this call of scanf_s is incorrect.对于初学者来说,这个scanf_s调用是不正确的。

scanf_s("%s", &arrayPalindrome);

You have to write你必须写

scanf_s("%s", arrayPalindrome, rsize_t( sizeof( arrayPalindrome ) ) );

The function checker does not build a string in the array bigArray because you forgot to append the stored sequence of characters in the array with the terminating zero character '\0' . function checker不会在数组bigArray中构建字符串,因为您忘记了 append 数组中存储的字符序列,其中包含终止零字符'\0'

Moreover the function does not make sense because the array bigArray is not used anymore in the program.此外,function 没有意义,因为程序中不再使用数组bigArray

The function lowerCase is declared with one parameter function lowerCase用一个参数声明

void lowerCase(char* string);

but is called with two arguments.但是用两个 arguments 调用。

lowerCase(arrayPalindrome, bigArray);

Pay attention to that there is no need to declare the auxiliary array bigArry .注意不需要声明辅助数组bigArry

And the program should not change the original string.并且程序不应更改原始字符串。

Others, in comments and answers, have addressed the shortcomings in the code you presented.其他人在评论和答案中已经解决了您提供的代码中的缺点。 This answer addresses the heuristic approach to the problem.这个答案解决了问题的启发式方法。

As you are experiencing, every line of code is an opportunity for a bug to occur.正如您所经历的,每一行代码都是发生错误的机会。

Acknowledging that the problem statement may have specified "write three functions", there is no need for so many.承认问题陈述可能已经指定了“写三个函数”,没有必要这么多。 A single function does all that is necessary:单个 function 可以完成所有必要的工作:

#include <stdio.h> // all that is needed

bool isPalindrome( const char s[] ) {
    // a "custom" 7bit ASCII "look up" table with exclusion ('.') and 'tolower()' equivalence
    char *tbl =
        "................................................0123456789......"
        ".abcdefghijklmnopqrstuvwxyz......abcdefghijklmnopqrstuvwxyz.....";

    // 'L'eft and 'R'ight indexing into the passed string
    size_t L = 0, R = 0;

    // find the end of the string (its 'r'ight index)
    while( s[R] ) R++; // poor boy's 'strlen(s)'. '\0' does not matter.

    do {
        // adjust indexes L & R rejecting characters
        // seek to "meet in the middle" of a palindromic string
        while( L <= R && tbl[ s[L] ] == '.' ) L++;
        while( L <= R && tbl[ s[R] ] == '.' ) R--;
    } while( L <= R && tbl[ s[L] ] == tbl[ s[R] ] && (L+=1) > 0 && (R-=1) > 0 );
    // string is palindromic if it has passed the tests above
    return L >= R;
}

int main() {
    // without the drudgery of re-entering test strings,
    // this "test harness" examines 3 different strings
    // giving the evaluation of each. Easy to add more test cases.
    char *strs[] = {
        "LeVrEl",
        "level",
        "123Madam I'm    Adam321",
    };

    for( int i = 0; i < sizeof strs/sizeof strs[0]; i++ )
        printf( "%s - '%s'\n", isPalindrome( strs[i] ) ? "Yes" : "No ", strs[i] );

    return 0;
}
No  - 'LeVrEl'
Yes - 'level'
Yes - '123Madam I'm    Adam321'

Far fewer lines of code, and should be "easy to follow" when one envisions a string as simply a contiguous array of characters.代码行数少得多,并且当人们将字符串设想为简单的连续字符数组时应该“易于理解”。

If the assignment is to write 3 functions, one could add two more "no-op" functions to fulfill that criteria:如果任务是编写 3 个函数,则可以再添加两个“无操作”函数来满足该标准:

int thing1(void) { return 1; }
int thing2(void) { return 2; }

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

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