回文,以降低功能

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

目前有一个学校的作业,要做一个C程序,该程序检查用户输入的字符串是否是回文。该程序需要具有2种不同的功能(不计算主要功能),一种是检查字符串是否是回文,而另一种则可以使程序将大写字母识别为小写字母。示例:该程序将“哇”和“哇”都识别为回文,到目前为止,它仅识别第一个而不是第二个。我目前不知道该如何进行,并给予了很多帮助。

这是我的代码当前的外观:

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


int checkPalindrome(char* text) 
{
    int i, c = 0, l; 
    l = strlen(text); 
    for (i = 0; i < l / 2; i++)
    {
        if (text[i] == text[l - i - 1])
            c++; 

    }
    if (c == i)
        return 1; 
    else
        return 0; 
}

int setToLowercase()
{

}

int main()
{
    char text[1000]; 

    printf("Enter  the string: ");

    gets(text); 


    if (checkPalindrome(text)) 
        printf("string is palindrome"); 
    else
        printf("string is not palindrome"); 

    return 0;
}
c function palindrome tolower
4个回答
0
投票

如果允许,tolower()会将字符转换为小写。循环输入字符串。

否则,请在ascii图表上进行细算,然后算出数学/如果是案例,则为该数字。


0
投票

对于根据C标准的启动器,不带参数的main函数应声明为

int main( void )

功能gets不是标准的C功能。这是不安全的。而是使用标准的C函数fgets

函数checkPalindrome不会更改传递的字符串。因此,应使用限定符const声明其参数。

int checkPalindrome(const char* text);

strlen函数的返回类型为size_t。因此,接受函数返回值的变量也应具有类型size_t

要将字符转换为小写,请使用标头tolower中声明的标准函数<ctype.h>

下面有一个演示程序,显示了如何编写原始程序。

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

char setToLowercase( char c )
{
    return tolower( ( unsigned char )c );
}

int checkPalindrome( const char *s ) 
{
    size_t n = strlen( s );

    size_t i = 0;

    while ( i < n / 2 && setToLowercase( s[i] ) == setToLowercase( s[n-i-1 ] ) )
    {
        i++;
    }

    return i == n / 2;
}

int main(void) 
{
    while ( 1 )
    {
        enum { N = 1000 };
        char s[N]; 

        printf( "Enter a string (Enter - exit): " );

        if ( fgets( s, N, stdin ) == NULL || s[0] == '\n' ) break;

        //  remove the appended new line character '\n'
        s[ strcspn( s, "\n" ) ] = '\0';

        printf( "The string is %spalindrome.\n",
                checkPalindrome( s ) ? "" : "not " );
        putchar ( '\n' );               
    }

    return 0;
}

程序输出可能看起来像

Enter a string (Enter - exit): AbCdEeDcBa
The string is palindrome.

Enter a string (Enter - exit): 

如果使用MS VS编译器来编译程序,则可以包含指令

#define _CRT_SECURE_NO_WARNINGS

例如,也可以内联函数setToLowercase

inline static char setToLowercase( char c )
{
    return tolower( ( unsigned char )c );
}

-1
投票

我设法通过tolower()函数解决了“问题”。谢谢

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

-1
投票

关于简单转换功能行tolower()的工作原理的简短解释会很有用。

它依赖于字符的ASCII表示形式:[0-127]范围内的每个值都对应一个特定字符,并且可以包含在char类型的变量中。

  • 大写字母字符的ASCII值在[65-90]范围内(十六进制:[0x41-0x5A])
  • 小写字母字符的ASCII值在[97-122]范围内(十六进制:[0x61-0x7A]]

小写字符始终可以精确地计算为大写值加上32(十六进制:0x20)。

然后,tolower ()实现可以是:

char tolower ( char c )
{
    return (c>=0x41 && c<=5A)?  c+0x20 : c;
}

了解字符及其ASCII值之间的关系是一种有用的武器,它使得琐碎的任何其他字符操作功能(例如toupper ()isdigit ()等)的实现变得简单。

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