在c中按字典顺序对字符串进行排序

Sorting string lexicographically in c

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

例如:

我有一个字符串: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] != '[=11=]';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]);
}

对这种事情使用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;
}

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

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

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

也像 Weather Vane 所说的那样,不要使用 gets(),而是使用 fgets() o 然后从字符串末尾删除 '\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 = '[=11=]';

  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

下面是一个紧凑的工作方式来做你想做的事。它打印每一行的单词,按一个 space 排序和分隔,而不重复重复的单词(如果你想重复它们,你将能够触摸程序使其工作)

$ 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 */