字符数组怎么按大小排序C语言
时间: 2023-09-08 17:14:10 浏览: 87
可以使用标准库函数qsort()对字符数组进行排序。具体操作如下:
1. 定义字符数组并赋值;
2. 定义一个比较函数用于排序;
3. 调用qsort()函数进行排序。
以下是示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmpfunc(const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
int main ()
{
char arr[] = "hello world";
int len = strlen(arr);
qsort(arr, len, sizeof(char), cmpfunc);
for (int i = 0; i < len; i++)
printf("%c", arr[i]);
return 0;
}
```
输出结果为:dehllloorw。
相关问题
c语言字符数组按ascii排序
可以使用C语言的标准库函数`qsort()`对字符数组按ASCII码进行排序。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b) {
return *(char *)a - *(char *)b;
}
int main() {
char str[] = "hello world";
int len = strlen(str);
qsort(str, len, sizeof(char), cmp);
printf("%s\n", str);
return 0;
}
```
其中,`cmp()`函数用于比较两个字符的ASCII码大小,作为`qsort()`函数的比较函数传入。主函数中,先将要排序的字符串转化为字符数组`str`,再调用`qsort()`函数对其进行排序。最后输出排序后的结果。
需要注意的是,`qsort()`函数只能对一维数组进行排序。如果要对二维字符数组进行排序,则需要对每一行进行单独的排序操作。
C语言中字符数组冒泡排序
下面是使用冒泡排序算法对字符数组进行排序的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void bubble_sort(char arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
char temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
char str[] = "chitgpt";
int n = strlen(str);
bubble_sort(str, n);
printf("Sorted string: %s\n", str);
return 0;
}
```
该程序首先定义了一个名为`bubble_sort`的函数,该函数接受一个字符数组和它的长度作为参数,并使用冒泡排序算法对该数组进行排序。然后在`main`函数中定义了一个字符数组`str`,并使用`strlen`函数获取它的长度。最后调用`bubble_sort`函数对`str`进行排序,并输出排序后的结果。