比较 C 语言中的字符
本教程介绍了如何在 C 语言中比较字符 char,char 变量是一个 8 位的整数值,从 0 到 255。这里,0
代表 C-null 字符,255 代表空符号。
在 C 语言中使用比较运算符比较字符 char
一个 char 变量有自己的 ASCII 值。所以根据 ASCII 值对字符进行比较。完整的程序如下。
#include<stdio.h>int main(void)
{
char firstCharValue='m';
char secondCharValue='n';
if(firstCharValue < secondCharValue)
printf("%c is smaller than %c.", firstCharValue, secondCharValue);
if(firstCharValue > secondCharValue)
printf("%c is smaller than %c.", firstCharValue, secondCharValue);
if(firstCharValue == secondCharValue)
printf("%c is equal to %c.", firstCharValue, secondCharValue);
return 0;
}
输出:
m is smaller than n.
使用 C 语言中的 strcmp()
函数来比较 char 值
strcmp()
函数定义在 string
头文件中,用于逐个比较两个字符串的字符。
如果两个字符串的第一个字符相同,则比较两个字符串的下一个字符。它一直持续到两个字符串的对应字符不同或者达到一个空字符'/0'
为止。
strcmp()
函数的语法如下。
int strcmp (const char* firstStringValue, const char* secondStringValue);
- 如果两个字符串相等或相同,则返回
0
。 - 如果第一个未匹配字符的 ASCII 值大于第二个,则返回一个正整数。
- 如果第一个未匹配字符的 ASCII 值小于第二个,则返回一个负整数。
比较两个字符串的完整程序如下。
#include<stdio.h>#include<stdlib.h>#include<string.h>int main(void)
{
char firstString= "b", secondString= "b",thirdString= "B";
int result;
result= strcmp(&firstString, &secondString);
printf("strcmp(firstString, secondString) = %d\n", result);
result = strcmp(&firstString, &thirdString);
printf("strcmp(firstString,thirdString) = %d\n", result);
return 0;
}
输出:
strcmp(firstString, secondString) = 0
strcmp(firstString, thirdString) = 1
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。