Friday, January 27, 2012

Comparing Strings

Comparing strings is vital in programming particularly in sorting.

For example, we want to arrange names in alphabetical order. Since names are stored as strings, we need to understand the string's compare() method.

Syntax:
string1.compare(string2);

Condition Return Value 
if string1 is equal to string2          0
if string1 is greater than string2             > 0
if string1 is less than string2         < 0


Sample Code:
#include <iostream>
#include <string>
using namespace std;
int main(){
     // First
     string string1 = "abc";
     string string2 = "bcd";
     string1.compare(string2);  // returns less than 0 because abc comes before bcd (a<b)
     // Second
     string1 = "HELLO";
     string2 = "ALOHA";
     string1.compare(string2); // returns greater than 0 because HELLO comes after ALOHA (H>A)
     //Third
     string1 = "Hello";
     string2 = "Hello";
     string1.compare(string2); // returns 0 because Hello and Hello are equal
     //Fourth
     string1 = "hello";
     string2 = "Hello";
     string1.compare(string2); // returns greater than 0 because hello comes after Hello
     return 0;
}

The fourth example returns greater than 0 because according to the ASCII table, h > H.

Small letters have greater decimal values than capital letters.
The decimal value of h is 104 while H is 72.


ASCII Table

No comments:

Post a Comment