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

标签 c arrays string sorting lexicographic

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

例如:

我有一个字符串:我是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]);
}

最佳答案

如果您尝试在 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

关于c - 在c中按字典顺序对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39356623/

相关文章:

string - 如何对Lua脚本进行反混淆?

c - 函数调用 mip

c - 如何解决 MISRA C :2012 Rule 11. 6?

字符设备 : choose the device to read/write

java - JAVA数组索引越界异常

java - 如何获取单词和等号以及等号和值之间的文本?

c - 内核崩溃后获取 Linux 内核调试信息

java - 我的循环用数字七、六次填充数组,为什么?

c - 按升序打印多个不同类型的数组

java - 如何解决不可变的 String[]