比较字符串序C语言
时间: 2023-07-25 20:08:41 浏览: 98
在C语言中,可以使用标准库函数strcmp()来比较两个字符串的字典序大小。该函数的原型为:
```c
int strcmp(const char* str1, const char* str2);
```
其中,str1和str2是要比较的两个字符串,函数返回值为int类型,表示两个字符串的字典序大小关系。如果返回值为0,则表示两个字符串相等;如果返回值大于0,则表示str1的字典序大于str2;如果返回值小于0,则表示str1的字典序小于str2。
例如,比较两个字符串"hello"和"world"的字典序大小:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 and str2 are equal.\n");
} else if (result > 0) {
printf("str1 is greater than str2.\n");
} else {
printf("str1 is less than str2.\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2.
```
相关问题
c语言字符串怎么比较大小
C语言中的字符串比较大小可以使用标准库函数`strcmp`。`strcmp`函数会按照字典序逐个比较两个字符串,直到出现不同的字符或者其中一个字符串结束。如果第一个字符串在字典序中排在第二个字符串之前,则返回一个负整数;如果第一个字符串在字典序中排在第二个字符串之后,则返回一个正整数;如果两个字符串相等,则返回0。
下面是一个使用`strcmp`函数比较两个字符串大小的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
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;
}
```
输出:
```
hello is less than world
```
用strcmp对字符串排序c语言
strcmp是用来比较两个字符串的函数,并不是用来排序的。如果要对一组字符串进行排序,可以使用C语言中的qsort函数。下面是一个例子,假设有一个字符串数组strArr,其中包含n个字符串,可以按照字典序对它进行排序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
int i, n;
char strArr[100][100];
printf("Enter the number of strings: ");
scanf("%d", &n);
printf("Enter the strings:\n");
for (i = 0; i < n; i++) {
scanf("%s", strArr[i]);
}
qsort(strArr, n, sizeof(char *), cmp);
printf("The sorted strings are:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strArr[i]);
}
return 0;
}
```
在这个例子中,我们定义了一个名为cmp的比较函数,其作用是比较两个字符串的大小。然后使用qsort函数对字符串数组进行排序,最后输出排序后的结果。注意,qsort函数的第三个参数是每个元素的大小,这里使用sizeof(char *)表示每个元素是一个指向char类型的指针。