簡體   English   中英

在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] != '\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]);
}

使用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] != '\0';i++)
    {
        if (s[i] == ' ')
            count++;    
    }
    count=count+1;
    i=0;
    pch = strtok (s," ,.-");

就像Weather Vane所說的那樣,不要使用gets(),而要使用fgets(),然后從字符串末尾刪除'\\ 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

以下是您想要做的一種緊湊的工作方式。 它打印出每行的單詞,並用一個空格進行排序和分隔,而無需重復重復的單詞(如果您希望重復它們,請確保可以觸摸該程序以使其正常運行)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM