在C语言中,可以使用strcmp函数对字符串进行排序。
strcmp函数比较两个字符串的大小,并返回一个整数值。
如果返回值大于0,则表示第一个字符串比第二个字符串大。如果返回值等于0,则表示两个字符串相等;如果返回值小于0,则表示第一个字符串比第二个字符串小;
下面是一个示例代码,对字符串数组进行排序:
#include <stdio.h>
#include <string.h>
int main() {
char strings[5][20] = {"apple", "banana", "cat", "dog", "elephant"};
// 排序
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
if (strcmp(strings[i], strings[j]) > 0) {
char temp[20];
strcpy(temp, strings[i]);
strcpy(strings[i], strings[j]);
strcpy(strings[j], temp);
}
}
}
// 输出
for (int i = 0; i < 5; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
以上代码会对字符串数组进行排序,输出结果为:
apple
banana
cat
dog
elephant
在C语言中,我们可以通过遍历字符串的每个字符来比较字符串的大小,而不使用strcmp函数。
#include <stdio.h>
#include <string.h>
int cmp_str(char *s1,char *s2)
{
while(*s1 && *s2 && *s1==*s2){
s1++;
s2++;
}
return *s1 - *s2;
}
int main() {
char *s1 = "orange";
char *s2 = "blue";
int n = cmp_str(s1,s2);
if(n>0){
printf("字符串s1大");
}
else if(n<0){
printf("字符串s2大");
}else{
printf("字符串相等");
}
return 0;
}
大于0的情况下,字符串s1比s2大;小于0的情况下,字符串s1比s2小;否则相等。