Tabassum Ahmed Tabassum Ahmed - 2 months ago 10
C Question

Sorting string lexicographically in c

I want to sort words of a string in lexicographical order.

For Example:

I have a string:

I am Apple


Output should be:
am Apple I


Problem (output):

enter the string

hello shamsh

the sorted array:

hello


It's not sorting the string and whole string is not being shown in the output, can anyone help me out here. Thanks!

Program code:

#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]);
}

Answer

If you try to print your string after you pch = strtok (s," ,.-"), you'll notice that your string is broken up. That's because strtok() is destructive and breaks up the string into tokens so you need to count the number of white spaces before calling 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," ,.-");

Also like Weather Vane said, don't use gets(), use fgets() instead oand remove the '\n' from end of the string afterwards. Also you can use realloc() to assign more memory to a dynamic array instead of using a static array since you wouldn't know the number of words in a string beforehand.

#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