The role of strcmp in c language

下次还敢
Release: 2024-05-07 09:30:25
Original
637 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!