djjduejd 2023-11-06 11:45 采纳率: 0%
浏览 12

请问一下大家,要用C语言编写

img

img


各位同行们,信息课说我们要按照他的要求编写这个程序。可是我不知道怎么编写

  • 写回答

2条回答 默认 最新

  • 七号公园的忧伤 新星创作者: Java技术领域 2023-11-06 14:13
    关注

    先分割字符串,然后按首字母排序

    #pragma warning(disable:4996)
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    //冒泡排序
    void sort(char** str, int row) {
        for (int i = 0; i < row-1; i++) {
            for (int j = row-1; j > i; j--) {
                if (str[j][0] < str[j-1][0]) {
                    char* temp = str[j];
                    str[j] = str[j-1];
                    str[j-1] = temp;
                }
            }
        }
        for (int i = 0; i < row; i++) {
            printf("%s\n", str[i]);
        }
    }
    
    //分割字符串
    char** splitStr(char* str, int* row) {
        char** res = (char**)malloc(sizeof(char*) * 100);
        char tempStr[60];
        *row = 0;
        int s = 0, e = 0;
        while (*(str + e) != '\0') {
            if (*(str + e) == ' ') {
                tempStr[e - s] = '\0';
                res[*row] = (char*)malloc(e - s + 1);
                char* temp = tempStr;
                strcpy(res[*row], temp);
                *row += 1;
                s = e + 1;
            }
            else {
                tempStr[e - s] = *(str + e);
            }
            e++;
        }
        res[*row] = (char*)malloc(e - s + 1);
        char* temp = tempStr;
        strcpy(res[*row], temp);
        *row += 1;
        return res;
    }
    
    int main() {
        char* str = "how are you";
        int row = 0;
        char** res = splitStr(str, &row);
        sort(res, row);
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月6日