Sorting a string, case insensitive

This is a discussion on Sorting a string, case insensitive within the C Programming forums, part of the General Programming Boards category; I need to take in a string up to 25 characters and output them in alphabetical order (case insensitive) according ...

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    1

    Sorting a string, case insensitive

    I need to take in a string up to 25 characters and output them in alphabetical order (case insensitive) according to the ASCII table. I have got them sorted, but I don't know how to make the case not matter.

    examples
    #?34trp ===> #34?prt
    I am good ===> _ _adgImoo
    aBA bCB ===> _aABbBC

    For example, my code would only output the last example ===> _ABCabc. I know I could change them all to capitals and then sort, but I don't know a way to change them back into lower case if there is more than one of them.

    Heres the code I have written:


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char s1[25];
        char temp;
        int i, j;
        gets(s1);
        printf(" \n %s \n", s1);
    
    
    
    
    
        for(j=0; s1[j]!= '\0'; j++)
        {
           for(i=0;s1[i+1]!= '\0'; i++)
           {
              if (s1[i]>s1[i+1])
              {
                temp=s1[i];
                s1[i]=s1[i+1];
                s1[i+1]=temp;
    
          }
      }
        
          j++;
    
    }
    
      printf(" \n %s \n", s1);
    
        return (0);
    }
    Thanks for the time,
    Paul

  2. #2
    Registered User
    Join Date
    Jul 2009
    Location
    Croatia
    Posts
    272
    While comparing, compare toupper(char1) and toupper(char2) or lower.

    So the line:
    if (s1[i]>s1[i+1])

    Replace it with if(toupper(s1[i] > toupper(s1[i+1]);

    I dont really understand whats with the 2 loops thing in your code.

    Id also suggest the swap seperated in another function for the code to be clearer when looking.

    And if you want, you could check the ShellSorting method. It's much faster then the one you showed (bubblesort).
    Last edited by Tool; 01-14-2010 at 05:18 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-05-2009, 11:32 AM
  2. Number to Word (Billions)
    By myphilosofi in forum C Programming
    Replies: 34
    Last Post: 02-04-2009, 02:09 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  4. Xmas competitions
    By Salem in forum Contests Board
    Replies: 88
    Last Post: 01-03-2004, 02:08 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21