Thread: comparison question

  1. #1
    Registered User
    Join Date
    Mar 2007
    Posts
    7

    comparison question

    in java, there is a compareTo method that returns the ascii difference of two strings, and i was wondering if there is a similar method in c++.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Yes there is a similar method in C++.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    Maybe what you're looking for is strcmp.

  4. #4
    Registered User Noir's Avatar
    Join Date
    Mar 2007
    Posts
    218
    C++ strings can be compared like ints:
    Code:
    string a = "something";
    string b = "something else";
    
    if ( a < b ) {
      cout << "a is smaller\n";
    } else if ( a == b ) {
      cout << "a and b are the same\n";
    } else {
      cout << "b is smaller\n";
    }
    C strings can't, and you have to treat them like arrays of characters:
    Code:
    int compareTo( char a[], char b[] ) {
      for ( int i = 0; a[i] && b[i] && a[i] == b[i]; i++ );
    
      if ( a[i] == '\0' ) {
        return -1;
      } else if ( b[i] == '\0' ) {
        return 1;
      } else {
        return a[i] - b[i];
      }
    }
    
    int rc = compareTo( a, b );
    
    if ( rc < 0 ) {
      cout << "a is smaller\n";
    } else if ( rc == 0 ) {
      cout << "a and b are the same\n";
    } else {
      cout << "b is smaller\n";
    }
    Or use strcmp from string.h since it does the work for you:
    Code:
    int rc = strcmp( a, b );
    
    if ( rc < 0 ) {
      cout << "a is smaller\n";
    } else if ( rc == 0 ) {
      cout << "a and b are the same\n";
    } else {
      cout << "b is smaller\n";
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. easy comparison question
    By The Gweech in forum C++ Programming
    Replies: 2
    Last Post: 02-26-2004, 04:37 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM