C语言 C 中的字符比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22736348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:56:32  来源:igfitidea点击:

Char Comparison in C

ccharcomparison

提问by dclark

I'm trying to compare two chars to see if one is greater than the other. To see if they were equal, I used strcmp. Is there anything similar to strcmpthat I can use?

我正在尝试比较两个字符以查看一个字符是否大于另一个字符。为了查看它们是否相等,我使用了strcmp. 有什么类似于strcmp我可以使用的东西吗?

回答by Victor

A charvariable is actually an 8-bit integral value. It will have values from 0to 255. These are ASCII codes. 0stands for the C-null character, and 255stands for an empty symbol.

char变量实际上是8位的整数值。它将具有从0到 的值255。这些是ASCII 码0代表 C-null 字符,255代表空符号。

So, when you write the following assignment:

因此,当您编写以下作业时:

char a = 'a'; 

It is the same thing as:

它与以下内容相同:

char a = 97;

So, you can compare two charvariables using the >, <, ==, <=, >=operators:

因此,您可以char使用>, <, ==, <=,>=运算符比较两个变量:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

回答by Vorsprung

In C the char type has a numeric value so the > operator will work just fine for example

在 C 中,char 类型有一个数值,因此 > 运算符将正常工作,例如

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

回答by Ayman Khamouma

I believe you are trying to compare two strings representing values, the function you are looking for is:

我相信您正在尝试比较表示值的两个字符串,您正在寻找的函数是:

int atoi(const char *nptr);

or

或者

long int strtol(const char *nptr, char **endptr, int base);

these functions will allow you to convert a string to an int/long int:

这些函数将允许您将字符串转换为 int/long int:

int val = strtol("555", NULL, 10);

and compare it to another value.

并将其与另一个值进行比较。

int main (int argc, char *argv[])
{
    long int val = 0;
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s number\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    val = strtol(argv[1], NULL, 10);
    printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");

    return 0;
}