在c中按字典顺序排序字符串

时间:2016-09-06 19:40:20

标签: c arrays string sorting lexicographic

我想按字典顺序对字符串的单词进行排序。

例如:

我有一个字符串:I am Apple

输出应为:am Apple I

问题(输出):

enter the string

hello shamsh

the sorted array:

hello

它没有对字符串进行排序,并且输出中没有显示整个字符串,任何人都可以帮助我。谢谢!

程序代码:

#include<stdio.h>
#include<string.h>
void main()
{
    char a[25][25],t[25];
    char s[200];
    char * pch;
    int count = 0;
    int i,j ,n;
    printf("enter the string\n");
    gets(s);
    pch = strtok (s," ,.-");
    for (i = 0;s[i] != '\0';i++)
    {
        if (s[i] == ' ')
            count++;    
    }
    count=count+1;
    i=0;
    while(pch != NULL)
    {
        strcpy(a[i],pch);
        pch = strtok (NULL, " ,.-");
        i++;
    }

    for(i=0;i<count-1;i++)
    {
        for(j=i+1;j<count;j++)
        {
            if(strcmp(a[i],a[j])>0)
            {
                strcpy(t,a[i]);
                strcpy(a[i],a[j]);
                strcpy(a[j],t);
            }
        }
    }
printf("the sorted array:\n");
for(i=0;i<count;i++)
printf("%s\n",a[i]);
}

3 个答案:

答案 0 :(得分:0)

使用qsort()来做这类事情。

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

#define BUF_SIZE 0x100

int strcmp_wrapper(const void *a, const void *b) {
        return strcmp(*(const char **)a, *(const char **)b);
}

int main () {
        char buffer[BUF_SIZE], *tokens[BUF_SIZE / 2 + 1];
        int i = 0, j = 0;

        printf("Enter a string: ");
        fgets(buffer, BUF_SIZE, stdin);

        tokens[0] = strtok(buffer, " ,.-\n");
        while ((tokens[++i] = strtok(NULL, " ,.-\n")));

        qsort(tokens, i, sizeof(tokens[0]), strcmp_wrapper);

        while (j < i)
                printf("%s\n", tokens[j++]);

        return 0;
}

答案 1 :(得分:0)

如果你在pch = strtok(s,“,.-”)之后尝试打印字符串,你会注意到你的字符串被打破了。这是因为strtok()具有破坏性并将字符串分解为标记,因此您需要在调用strtok()之前计算空格的数量:

printf("enter the string\n");
    gets(s);

    for (i = 0;s[i] != '\0';i++)
    {
        if (s[i] == ' ')
            count++;    
    }
    count=count+1;
    i=0;
    pch = strtok (s," ,.-");

也像Weather Vane所说,不要使用gets(),而是使用fgets()代替oand从字符串末尾删除'\ n'。此外,您可以使用realloc()为动态数组分配更多内存,而不是使用静态数组,因为您事先不知道字符串中的单词数。

#include <stdlib.h>
#include<stdio.h>
#include<string.h>
void main()
{
    char** a = NULL;
    char t[25];
    char s[512];
    char * pch;
    int count = 0;
    int i,j ,n;

    printf("enter the string\n");
  if(fgets(s,512, stdin)==NULL)
  {
    printf("failed to read string\n");
    exit(-1);
  }
  /*remove '\n' from end of the string*/
  char *pos;
  if ((pos=strchr(s, '\n')) != NULL)
    *pos = '\0';

  pch = strtok(s, " ,.-");
  while(pch)
  {
    a = realloc(a, sizeof(char*)*++count);
    if(a==NULL)
    { 
      perror("failed to allocate memory\n");
      exit(-1);
    }

    a[count-1] = pch;
    pch = strtok(NULL, " ,.-");
  }
   for(i=0;i<count;i++)
    printf("%d: %s\n", i, a[i]);
    ///...compare array

答案 2 :(得分:0)

下面是一个紧凑的工作方式来做你想要的。它打印每行的单词,按一个空格排序和分隔,不重复单词重复(如果你想重复它们肯定你可以触摸程序使它工作)

$ cat pru799.c

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

#define DELIMITERS  " \t\n,.-()&%$\"\'[]{}+-*/;:@#|!\\<>=?"
#define LINE_SIZE   1024
#define MAX_WORDS   256

int compare(const char **p, const char **q)
{
    return strcmp(*p, *q);
}

int main()
{
    char line[LINE_SIZE];
    char *words[MAX_WORDS];
    int n_words;

    while (fgets(line, sizeof line, stdin)) { /* while not eof */
        char *p;
        int i;

        /* first get the words */
        n_words = 0;
        for (p = strtok(line, DELIMITERS); p; p = strtok(NULL, DELIMITERS)) {
            if (strlen(p) == 0) continue; /* word is zero length */
            if (n_words >= MAX_WORDS) {
                fprintf(stderr, "MAX_WORDS(%d) exceeded\n", MAX_WORDS);
                exit(EXIT_FAILURE);
            }
            words[n_words++] = p;
        } /* for */

        /* now we have all the words in the array of strings words, sort it */
        qsort(words, n_words, sizeof words[0], (int(*)(const void *, const void *))&compare);

        /* now print the words */
        for (i = 0; i < n_words; i++) {
            if (i) { /* all but the first one */
                /* don't repeat words */
                if (!strcmp(words[i], words[i-1])) 
                    continue;
                printf(" "); /* print a space between words */
            }
            printf("%s", words[i]);
        }
        printf("\n");
    } /* while */
} /* main */