Cover Image for STRCMP() IN C++
142 views

STRCMP() IN C++

The strcmp() function is not a part of standard C++, but it is a standard C library function used for comparing two null-terminated C-style strings. It is commonly used when working with C-style strings (character arrays) in C++.

Here’s how to use strcmp():

C++
#include <iostream>
#include <cstring> // Include the C string library for strcmp

int main() {
    const char* str1 = "hello";
    const char* str2 = "world";

    int result = strcmp(str1, str2);

    if (result < 0) {
        std::cout << "str1 comes before str2" << std::endl;
    } else if (result > 0) {
        std::cout << "str2 comes before str1" << std::endl;
    } else {
        std::cout << "str1 and str2 are equal" << std::endl;
    }

    return 0;
}

In this example:

  • We include the <cstring> header to use the strcmp() function.
  • We define two C-style strings str1 and str2.
  • We call strcmp(str1, str2) to compare the two strings.
  • The function returns an integer value:
  • If result is less than 0, it means str1 comes before str2.
  • If result is greater than 0, it means str2 comes before str1.
  • If result is 0, it means the two strings are equal.

Keep in mind that strcmp() compares strings lexicographically, character by character, and stops when it finds a difference or reaches the end of one of the strings. It does not compare the lengths of the strings, so if you have strings of different lengths, you should be careful to avoid buffer overflows. In modern C++, it’s often recommended to use std::string for string manipulation instead of C-style strings and functions like strcmp() for improved safety and ease of use.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS