+ Reply to Thread
Results 1 to 8 of 8

Thread: Sorting C++ Strings

  1. #1
    whitey6993's Avatar
    whitey6993 is offline Programming Expert
    Join Date
    Dec 2008
    Posts
    435
    Rep Power
    15

    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 Attached Files

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: Sorting C++ Strings

    Very nice, +rep.

  4. #3
    Join Date
    Aug 2007
    Location
    Gizeh, Al Jizah, Egypt, Egypt
    Posts
    8,675
    Blog Entries
    12
    Rep Power
    81

    Re: Sorting C++ Strings

    good tutorial +rep
    yo homie i heard you like one-line codes so i put a one line code that evals a decrypted one line code that prints "i love one line codes"
    Code:
    eval(base64_decode("cHJpbnQgJ2kgbG92ZSBvbmUtbGluZSBjb2Rlcyc7"));
    www.amrosama.com | the unholy methods of javascript

  5. #4
    whitey6993's Avatar
    whitey6993 is offline Programming Expert
    Join Date
    Dec 2008
    Posts
    435
    Rep Power
    15

    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.

  6. #5
    mudi is offline Newbie
    Join Date
    Mar 2009
    Posts
    1
    Rep Power
    0

    Re: Sorting C++ Strings

    Thank you.
    good tutorial

  7. #6
    winuser2 is offline Newbie
    Join Date
    Jun 2009
    Posts
    1
    Rep Power
    0

    Re: Sorting C++ Strings

    great tutorial, a need it !

  8. #7
    Join Date
    Oct 2008
    Location
    Istog, Kosova
    Posts
    4,001
    Blog Entries
    1
    Rep Power
    40

    Re: Sorting C++ Strings

    Very Nice, indeed.
    Interested in participating in community events?
    Want to harness your programming skill and turn it into absolute prowess?
    Come join our programming events!

  9. #8
    musaid is offline Newbie
    Join Date
    Jan 2011
    Posts
    1
    Rep Power
    0

    Re: Sorting C++ Strings

    nice one. thanx. n gudluck

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. Beginner C# Strings
    By chili5 in forum CSharp Tutorials
    Replies: 3
    Last Post: 08-21-2011, 02:23 PM
  2. C++ Strings
    By xXAlphaXx in forum C and C++
    Replies: 4
    Last Post: 03-04-2010, 03:36 PM
  3. Strings.
    By Aereshaa in forum C Tutorials
    Replies: 4
    Last Post: 10-15-2008, 05:45 AM
  4. VB Strings
    By reniery in forum Visual Basic Programming
    Replies: 10
    Last Post: 10-08-2008, 01:44 PM

Tags for this Thread

Bookmarks

Posting Permissions

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