This blog is under construction

Wednesday 17 July 2013

C program to perform case insensitive sorting

Write a C program to perform case insensitive sorting.


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

  int main() {
        char strings[100][100], temp[100];
        int i, j, n;

        /* get the number of strings from the user */
        printf("Enter the number of string:");
        scanf("%d", &n);

        getchar();

        /* get the input string from the user */
        for (i = 0; i < n; i++) {
                printf("String[%d] : ", i);
                fgets(strings[i], 100, stdin);
                strings[i][strlen(strings[i]) - 1] = '\0';
        }

        /* case insensitive ascending order sorting */
        for (i = 0; i < n - 1; i++) {
                strcpy(temp, strings[i]);
                for (j = i + 1; j < n; j++) {
                        if (strcasecmp(temp, strings[j]) > 0) {
                                strcpy(temp, strings[j]);
                                strcpy(strings[j], strings[i]);
                                strcpy(strings[i], temp);
                        }
                }
        }

        /* Display the sorted string */
        printf("\nString after sorting:\n");
        for (i = 0; i < n; i++) {
                printf("%s\n", strings[i]);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of string:4
  String[0] : orange
  String[1] : Orange
  String[2] : Apple
  String[3] : apple

  String after sorting:
  Apple
  apple
  orange
  Orange



No comments:

Post a Comment