+ Reply to Thread
Results 1 to 7 of 7

Thread: Sorting C++ Strings

  1. #1
    Programming Expert whitey6993 has a spectacular aura about whitey6993 has a spectacular aura about whitey6993's Avatar
    Join Date
    Dec 2008
    Location
    In front of my Computer
    Posts
    407

    Sorting C++ Strings

    This tutorial shows how to order a vector of strings in alphabetical order.

    Lets say you have a list of strings that you have stored in a vector. You need to order the strings but you do not have a function to do it with. Well ordering strings is actually easier than you might think. It works alot like ordering numbers in an array. I have modified a bubble sort function to
    show you how it works.

    First we include the vector and string header files, and use the std namespace so we can access vectors and strings.

    Code:
    #include <vector>
    #include <string>
    using namespace std;
    For those not familier with vectors, they work like arrays except they are treadted as objects. Unlike arrays they can be returned from functions and are also expandable. You add to them by using their push_back member function and you declare them by writing vector<data type>. I have also included the psuedo code for the bubble sort algorithm for refrence (Taken from Starting out With C++ 3rd Eddition).

    Code:
    Do
       Set count variable to 0
       For count is set to each subscript in Array from 0 to the next-to-last subscript
          If array[count] is greater than array[count+1]
       swap them
       set swap flag to true
       end if
    End for
    While any elements have been swapped.
    Now that we have that done, we can start working on our sorting function. First we have to declare the function prototype and then the definition.

    Code:
    vector<string> sortAlpha(vector<string>);
    //Main Program Here
    vector<string> sortAlpha(vector<string> sortThis)
    {
    As you can see, the function accepts a vector of strings as it's only argument. It then returns a sorted vector of strings. Now following the psuedo code for the bubble sort, we can make a sorting function. We start by initializing all the variables we need for the function. In this case, we need
    a swap flag and a temporary storage place.

    Code:
    int swap;
    string temp;
    Next we open our do-while loop and set our swap flag to 0. After this we open up our for loop.

    Code:
    	swap = 0;
    	for (int count = 0; count < sortThis.size() - 1; count++)
    	{
    Now we can set up our if statment, our swap procedure, and close our remaining brackets.

    Code:
    		if (sortThis.at(count) < sortThis.at(count + 1)
    		{
    			temp = sortThis.at(count);
    			sortThis.at(count) = sortThis.at(count + 1);
    			sortThis.at(count + 1) = temp;
    			swap = 1;
    		}
    	}
    }while (swap != 0);
    Now if you are like me, you may be thinking "You can't compare two strings with the less than operator!", but actually you can. It compares them letter by letter and works just like if you compared two integers. It is
    perfect for use in this sorting algorithm. Now that the main part of the program is taken care of, all we need to do is return our sorted vector and close our last brace.

    Code:
    return sortThis;
    }
    And thats it. If you want to test the program, just write this in your main function:
    Code:
    {
        vector<string> stringList;
        vector<string> sortedStringList;
        string buffer;
        
        for(int i = 0; i < 5; i++)
        {
            cout << "Enter the " << i << "th string in the list: ";
            cin >> buffer;
            stringList.push_back(buffer);
        }
        
        sortedStringList = sortAlpha(stringList);
        cout << "The sorted string list is: " << endl << endl;
        
        for (int i = 0; i < 5; i++)
            cout << sortedStringList.at(i) << endl;
            
        
        system("pause");
    }
    And don't forget to include <iostream>. Well thats my first tutorial. I doubt it will help many people as I bet I'm the only one who didn't know you can compare strings with the less than/greater than operator .
    However I thought it was interesting and that I should share it. This source code was written and compiled using Dev-C++ compiler so it may need to be edited to work with other compilers. I have attatched a complete source code listing for convenience. I also have a simple challange to anyone who needs to burn about a minute or so. Try making the program sort words in reverse alphabetical order. If anyone has any revisions, our would like to suggest a better way of accomplishing the goal, please let me know.
    Attached Files

  2. #2
    Administrator Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan's Avatar
    Join Date
    Nov 2005
    Location
    Hendersonville, NC
    Posts
    24,556
    Blog Entries
    97

    Re: Sorting C++ Strings

    Very nice, +rep.

  3. #3
    Code Warrior
    /////////|||||\\\\\\\\\
    amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama is a splendid one to behold amrosama's Avatar
    Join Date
    Aug 2007
    Location
    Pyramids st, Giza, Egypt
    Age
    21
    Posts
    8,182
    Blog Entries
    12

    Re: Sorting C++ Strings

    good tutorial +rep

  4. #4
    Programming Expert whitey6993 has a spectacular aura about whitey6993 has a spectacular aura about whitey6993's Avatar
    Join Date
    Dec 2008
    Location
    In front of my Computer
    Posts
    407

    Re: Sorting C++ Strings

    Thank you I have my next tutorial planned as an introduction to namespaces. If anyone is interested, I will post it here.

  5. #5
    Newbie mudi is an unknown quantity at this point
    Join Date
    Mar 2009
    Posts
    1

    Re: Sorting C++ Strings

    Thank you.
    good tutorial

  6. #6
    Newbie winuser2 is an unknown quantity at this point
    Join Date
    Jun 2009
    Posts
    1

    Re: Sorting C++ Strings

    great tutorial, a need it !

  7. #7
    Guru MathX has a spectacular aura about MathX has a spectacular aura about MathX's Avatar
    Join Date
    Oct 2008
    Location
    Kosovo
    Age
    19
    Posts
    4,006

    Re: Sorting C++ Strings

    Very Nice, indeed.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. Coder Battle #2: Sorting
    By Jordan in forum Games
    Replies: 99
    Last Post: 12-10-2008, 09:02 AM
  2. C Strings, C++ Strings?
    By telboon in forum C and C++
    Replies: 20
    Last Post: 11-20-2008, 08:16 PM
  3. Strings (CrashCourse)
    By LogicKills in forum C Tutorials
    Replies: 3
    Last Post: 09-17-2008, 07:28 PM
  4. Finding non-standard sorting order via graph theory
    By elle in forum General Programming
    Replies: 1
    Last Post: 05-17-2007, 09:36 PM
  5. Strings
    By clookid in forum PHP Tutorials
    Replies: 2
    Last Post: 01-13-2007, 03:23 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts