C - 按字母顺序排序字符串而不使用strcmp()

时间:2014-03-23 10:59:05

标签: c sorting strcmp

我正在编写一个小型C程序,它应按字母顺序对逗号分隔的字符串进行排序。

输入如下:“FSKT”,“EORD”,“OSEA”,“DA”,“ERTS”,“VG”,“FHR”,“EIAS”,“DOD”

这是进行排序的工作代码:

#include <stdio.h>
#include <string.h> 
int main() {
    char *a[] = {"FSKT","EORD","OSEA","DA","ERTS","VG","FHR","EIAS","DOD"};
    const char *s1,  *s2;
    int compRes,i,j;
    int length = 9;
    for (i = 0; i < length; i++) {
        for (j = i+1; j < length; j++){
            s1 = a[i];
            s2 = a[j];
            compRes = 0;
            while(*s1 && *s2){              
                if(*s1!=*s2){               
                    compRes = *s1 - *s2;     
                    break;                   
                }                           
                ++s1;
                ++s2;
            }
            if (compRes > 0 || (compRes == 0 && *s1)) {
                char* temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        printf("%s ", a[i]);

    }
    printf("\n");
    return 0;
}

我没有使用strcmp()或类似的东西,因为它需要保持非常基本的以便以后的翻译。 现在我想使用scanf()作为输入字符串,如果到达一个点,输入应该停止。不知怎的,我已经陷入了投入......

这是我到目前为止的尝试,不幸的是它没有用。:

 #include <stdio.h>
    #include <string.h> 
    int main() {

        int compRes;
        int i;
        int j;
        int length = 9;
        char *s1;
        char*s2;
        char a[10][10] = { 0,0,0,0,0,0,0,0,0,0};

        //scan all strings separated with a comma

        scanf("%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,]" ,a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);



            for (i = 0; i < length; i++) {
                for (j = i+1; j < length; j++){
                    s1 = a[i];
                    s2 = a[j];
                    compRes = 0;
                    while(*s1 && *s2){
                        if(*s1!=*s2){
                            compRes = *s1 - *s2;
                            break;
                        }
                        ++s1;
                        ++s2;
                    }
                    if (compRes > 0 || (compRes == 0 && *s1)) {
                        char* temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }

                }
                printf("%s ", a[i]);

            }
            printf("\n");
            return 0;
        }

有人可以帮助我吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

问题不在于扫描,而在于以下几行:

                char* temp = a[i];
                a[i] = a[j];
                a[j] = temp;

前面的代码适用于指针数组,不适用于二维数组的字符。如果它甚至编译我会感到惊讶。您基本上有两种选择来修复您的程序。

您可以将字符串扫描到二维数组中,并设置指向原始一维指针数组的正确指针,程序保持不变。即:

    char b[10][10] = { 0,0,0,0,0,0,0,0,0,0};
    char *a[10];
    for(i=0; i<length; i++) a[i] = b[i];

或者您需要在进行交换时复制整个字符串。即:

               char temp[10];
               strcpy(temp, a[i]);
               strcpy(a[i], a[j]);
               strcpy(a[j], temp);