strcmp(“AB3”,“AB”)
时间: 2023-12-14 18:05:56 浏览: 13
根据提供的引用内容,strcmp()函数用于比较两个字符串,并根据它们之间的字典顺序返回一个整数。如果第一个字符串小于第二个字符串,则返回一个小于零的整数。如果第一个字符串大于第二个字符串,则返回一个大于零的整数。如果两个字符串相等,则返回零。
在这个例子中,strcmp("AB3","AB")将返回一个大于零的整数,因为字符'3'的ASCII码值大于字符'\0'的ASCII码值。
以下是一个演示如何使用strcmp()函数的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "AB3";
char str2[10] = "AB";
int result = strcmp(str1, str2);
if(result < 0) {
printf("'%s' is less than '%s'\n", str1, str2);
} else if(result > 0) {
printf("'%s' is greater than '%s'\n", str1, str2);
} else {
printf("'%s' is equal to '%s'\n", str1, str2);
}
return 0;
}
```
输出结果为:'AB3' is greater than 'AB'
相关问题
strcmp函数的用法
strcmp函数是C语言字符串操作函数之一,其作用是比较两个字符串的大小。其用法如下:
```c
int strcmp(const char* str1, const char* str2);
```
其中,str1和str2为要比较的两个字符串。当str1等于str2时,函数返回0;当str1大于str2时,函数返回正数;当str1小于str2时,函数返回负数。
值得注意的是,strcmp函数比较的是字符串的字典序,即从左到右逐个字符比较大小。比如"ab"和"ac"的比较结果是-1,而不是1。
用C++写一个当输入A时输出1,输入B时输出2,输入AB时输出1 2
以下是使用C语言编写的代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char input[3];
printf("请输入字符(A/B/AB):");
scanf("%s", input);
if(strcmp(input, "A") == 0) {
printf("1\n");
} else if(strcmp(input, "B") == 0) {
printf("2\n");
} else if(strcmp(input, "AB") == 0) {
printf("1 2\n");
} else {
printf("输入错误,请输入A、B或AB!\n");
}
return 0;
}
```
该程序首先要求用户输入字符(A、B或AB),然后根据用户输入的字符进行判断处理,并输出相应的结果。如果输入不合法,程序会提示用户重新输入。