You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取字符串首字符ASCII值以实现字符串数组按字母顺序排序

C语言获取字符串首字符ASCII值及字符串数组排序实现

获取字符串首字符ASCII值的方法

  • C语言中的字符串本质是以\0结尾的char数组,首字符对应数组下标为0的元素,char类型本身存储的就是字符的ASCII编码值,直接将其强转为int类型即可得到对应的ASCII值
  • 注意:取ASCII值前需要先判断字符串非空,避免访问越界
    示例代码:
char *str = "Apple";
// 仅当字符串非空时取值
if (str[0] != '\0') {
    int first_ascii = (int)str[0];
    printf("首字符%c的ASCII值为%d", str[0], first_ascii);
}

字符串数组按字母顺序排序的实现

你给出的测试数组如下:

char *fruits[]={
               "Mango",
               "Apple",
               "Jackfruit",
               "Watermelon",
               "Banana"
               };

方案说明

如果仅按首字符ASCII排序,遇到首字符相同的字符串时排序结果会不符合预期,更稳妥的方式是直接调用C标准库<stdlib.h>的qsort函数,搭配<string.h>的strcmp函数实现完整的字典序排序:
完整示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// qsort要求的比较函数
int cmp_str(const void *a, const void *b) {
    // void指针转为char**再解引用得到char*字符串,用strcmp比较
    return strcmp(*(const char **)a, *(const char **)b);
}

int main() {
    char *fruits[] = {
        "Mango",
        "Apple",
        "Jackfruit",
        "Watermelon",
        "Banana"
    };
    int len = sizeof(fruits) / sizeof(fruits[0]);
    
    // 调用快速排序
    qsort(fruits, len, sizeof(char *), cmp_str);
    
    // 打印排序结果
    for (int i = 0; i < len; i++) {
        printf("%s\n", fruits[i]);
    }
    return 0;
}

输出结果:

Apple
Banana
Jackfruit
Mango
Watermelon

内容的提问来源于stack exchange,提问作者Yaaro Obba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:06:02