Home  >  Article  >  Backend Development  >  The role of strcmp in c language

The role of strcmp in c language

下次还敢
下次还敢Original
2024-05-07 09:30:25678browse

strcmp function compares two strings and returns an integer value: 0 (equal), positive number (the first string is greater than the second string), negative number (the first string is less than the second string) string).

The role of strcmp in c language

The role of strcmp in C language

The strcmp function is a function in the C standard library, used for comparison Two C strings. It receives two strings as parameters and returns an integer value representing the comparison result.

Explanation of return value:

  • 0: If the two strings are the same.
  • Positive number: If the first string is alphabetically larger than the second string (that is, the ASCII code value of the first string is greater).
  • Negative number: If the first string is lexically smaller than the second string (that is, the ASCII code value of the first string is smaller).

Working principle:

The strcmp function compares characters in two strings one by one. If a non-matching character is encountered, the difference in ASCII codes of the first non-matching character is returned. If the two strings are the same, the function compares all characters and returns 0.

Syntax:

<code class="c">int strcmp(const char *str1, const char *str2);</code>

Parameters:

  • str1: The number to be compared a string.
  • str2: The second string to compare.

Example:

<code class="c">#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Hello";
  char str2[] = "World";

  int result = strcmp(str1, str2);

  if (result == 0) {
    printf("字符串相同。\n");
  } else if (result > 0) {
    printf("第一个字符串大于第二个字符串。\n");
  } else {
    printf("第一个字符串小于第二个字符串。\n");
  }

  return 0;
}</code>

Output:

<code>第一个字符串小于第二个字符串。</code>

The above is the detailed content of The role of strcmp in c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn