String comparison function strcmp() in C language

int strcmp( const char *string1, const char *string2 );

The strcmp function is a string comparison function in C language, which is used to compare the size relationship between two strings.

The prototype of this function is as follows:

```c int strcmp(const char *string1, const char *string2); ```

Among them, `string1` and `string2` are two strings to be compared respectively, and the return value of the function is an integer, indicating the size relationship between the two strings.

Returns a negative integer if `string1` is less than `string2`;

Returns 0 if `string1` is equal to `string2`;

Returns a positive integer if `string1` is greater than `string2`.

The comparison rule of this function is to compare lexicographically, that is, to compare the characters in the string one by one from left to right until different characters appear or one of the strings ends. If two strings have the same prefix portion but one of them has ended, the shorter-length string is considered to be smaller than the longer-length string.

#include"stdio.h"
#include"string.h"

int main() {

	printf("%d\n", strcmp("abcefg", "abcd"));   // 结果是 1  第一个字符串大于第二个字符串
	printf("%d\n", strcmp("abc", "abc"));   // 结果是 0     第一个字符串等于第二个字符串
	printf("%d\n", strcmp("abc", "abcd"));   // 结果是 -1   第一个字符串小于第二个字符串
	return 0;
}

To use the strcmp() function, you need to reference the string.h header file.

#include"stdio.h"
#include"string.h"
int main() {
	int i = 0;
	// 假设正确的密码是“123456”
	char password[20] = { 0 };
	for (i = 0; i < 3; i++) {
		printf("请输入密码:");
		scanf("%s", password);   // 数组名不需要取地址,本身就是地址名。
		//if (password == "123456"); // 这种写法是错误的,两个字符串比较,不能使用==,应该使用strcmp
		if (strcmp(password, "123456") == 0)  // 比较password和“123456”是否等于0
		{
			printf("登录成功\n");
			break;
		}
		else {
			printf("密码错误\n");
		}

	}
	if (i == 3) {
		printf("密码3次错误!\n");
	}


	return 0;
}

Guess you like

Origin blog.csdn.net/xingyuncao520025/article/details/130698277