strcmp() C Library Function Usage with Examples – POFTUT

strcmp() C Library Function Usage with Examples

C programming standard library provides strcmp() function in order to compare two strings and return the results whether they are identical or different.

Syntax and Parameters

As stated previously strcmp() function takes two char array or string arguments.

  • const char* str1 is the first string or char array which will be compared the second one. const is mainly used to prevent given char array pointer to be changed.
  • const char* str2 is the second string or char array which will be compared with the first one.

Return Values

strcmp() function returns an int or integer type. We can get 3 types of return value that are explained below.

  • is returned if both strings are identical, equal or the same.
  • Negative Integer if the ASCII value of the first unmatched character is less then second
  • Positive Integer if the ASCII value of the first unmatched character is greater than second

Compare Two Strings

We can compare two strings which are expressed as char array in C programming language. We will compare strings “I love poftut.com” and “I loves poftut.com” .

We will compile with gcc like below and then run the binary.

LEARN MORE  Search Text Files Content With Findstr Command In Windows

Compare Two Strings

Compare Two Strings

Compare Two Char Array

We can compare two char arrays where

 

Compare Two Char Array

Compare Two Char Array

We can see that both of the character arrays are the same so the return value will be 0 and printed to the screen.

 

Compare Two Char Array

Compare Two Char Array

Strings Are Different and First Is Bigger and Return Positive Value

In this example, the first string is bigger and return a positive integer which is the value of the character.

Strings Are Different and First Is Bigger and Return Positive Value

Strings Are Different and First Is Bigger and Return Positive Value

Strings Are Different and Second Is Bigger Return Negative Value

In this example, the second string is bigger and return a positive integer which is the value of the character.

LEARN MORE  C String Variable Type

Strings Are Different and Second Is Bigger Return Negative Value

Strings Are Different and Second Is Bigger Return Negative Value

Strings Are Same Return 0

If both strings are the same the strcmp() function will return zero 0 .

Strings Are Same Return 0

Strings Are Same Return 0

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)