string comparision, sorting

This is a discussion on string comparision, sorting within the C++ Programming forums, part of the General Programming Boards category; I am trying to sort an array of strings... eg.. george sam ralph lisa arnold Im trying to sort this ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    48

    string comparision, sorting

    I am trying to sort an array of strings... eg..

    george
    sam
    ralph
    lisa
    arnold

    Im trying to sort this array like:

    Code:
    if(string1.substr(0,1) > string2.substr(0,1) 
      sort();
    do strings work like this? can I compare the first value of a string like.
    Code:
    if( A > B)
    cout << "A is greater than B" << endl;
    if not, then does anyone have any suggestions? the method above does not seem to work.

  2. #2
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    you can compare strings this way:

    Code:
    #include<iostream>
    using namespace std;
    
    #include<string>
    
    int main()
    {
        string name1 = "alex";
        string name2 =  "zirch";
        
        //you can use the compare() string member function
        //compare() returns -1 if name1 < name2
       //0 if name1 == name2
       //1 if name1 > name2
       if(name1.compare(name2) == -1)//compare name1 with name2 
           ........
       if(name1.compare(name2) == 0)
           .........
       if(name1.compare(name2) == 1)
          ...........
         
        return 0;
    }
    of course you have a lot of options to do that, like using the STL, converting the strings to arrays of char(C like), etc. but to start i think thi is good

    hope it helps
    please excuse my poor english

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    sorry my mistake,
    i was comparing by string size but i think you want to sort alphabetical, heres my posible solution using the not so fast bubble sort:

    Code:
    #include<iostream>
    using namespace std;
    
    #include<string>
    
    int main()
    {
        string namesList[5] = {"alex","maria","betty",
                                             "rolando","marlon"};
        string temp; //to store temporal string when swaping
        	//sorting the array of strings
    	for(int i = 0; i < 5; i++){
                        for(int j = 0; j < 5; j++){
    	        if(namesList[j] > namesList[j+1]) //if current string 
                            //is bigger than the next string in the array
                           {
                                 temp = namesList[j];
                                 namesList[j] = namesList[j+1];//i think you can 
                                 //use the swap method here
                                 namesList[j+1] = temp;
                          }
                       }
                   }
       //displaying the sorted list
        for(i = 0; i < 5; i++)
            cout << namesList[i] << ' ';
       
        return 0;
    }
    i dont know how portable this code is because i think the strings comparation is made using ascii values, but anyway maybe can give you an idea

  4. #4
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Your solution is fine, except you are indexing out of bounds and a few nicities for bubble sort, such as the last element after each pass is always the maximum and therefore the next pass should be 1 shorter. You can also bail after any complete pass without any swaps, thus bubblesort is atually fastest on a sorted list. std::strings have a member swap, and it is indeed much faster than doing things the hard way, but get it working first.

    The normal comparison operators (<,>,==, etc) work just fine with strings. The only problems I expect you could be having is that these comparisons are case sensitive, you could also be having some leading whitespace problems " apple" != "apple" and "Orange" != "orange". The three way compare function is also somewhat overkill in this context. String comparison is expensive as such things go, so testing a string for less than and then comparing for equality is a big waste of time. In that case you use compare, although if you don't store the result and end up calling it more than once you kinda defeat the point.

    Code:
    {
    int result = a.compare(b);
    if(result > 0) { // a>b
        ...
    } else if(result < 0) { // a<b
        ...
    } else { // a==b
        ... 
    }
    }

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,802
    Simplest method would be to just call the sort function on the array.

    Code:
    #include <string>
    #include <iostream>
    #include <iterator>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        string namesList[5] = {"alex","maria","betty","rolando","marlon"};
    
        cout << "Before sort: ";
        copy(namesList,namesList+5,ostream_iterator<string>(cout," "));
    
        sort(namesList,namesList+5);
    
        cout << "\nAfter sort : ";
        copy(namesList,namesList+5,ostream_iterator<string>(cout," "));
    
        return 0;
    }
    Should output:

    Code:
    Before sort: alex maria betty rolando marlon
    After sort : alex betty maria marlon rolando
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    Quote Originally Posted by hk_mp5kpdw
    Simplest method would be to just call the sort function on the array.

    Code:
    #include <string>
    #include <iostream>
    #include <iterator>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        string namesList[5] = {"alex","maria","betty","rolando","marlon"};
    
        cout << "Before sort: ";
        copy(namesList,namesList+5,ostream_iterator<string>(cout," "));
    
        sort(namesList,namesList+5);
    
        cout << "\nAfter sort : ";
        copy(namesList,namesList+5,ostream_iterator<string>(cout," "));
    
        return 0;
    }
    Should output:

    Code:
    Before sort: alex maria betty rolando marlon
    After sort : alex betty maria marlon rolando
    I agree with you and I'm assuming he still dont know how to work with iterators, etc.

    about out of boundaries sorting is true i dint notice that, thanks for comment

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. Replies: 5
    Last Post: 11-07-2005, 10:34 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM

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