C语言 strcmp

C语言 strcmp

#include <string.h>
int strcmp(const char *s1, const char *s2);

功能:比较 s1 和 s2 的大小,比较的是字符ASCII码大小。
参数:

  • s1:字符串1首地址
  • s2:字符串2首地址

返回值:

  • 相等:0
  • 大于:>0
  • 小于:<0

案例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    char ch1[] = "hello world";
    char ch2[] = "hallo world";

    // 两个字符串比较
    int    value = strcmp(ch1, ch2);

    // 返回为1不相等
    printf("%d\n", value);

    return 0;
}
strcmp 使用案例:使用函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void my_strcmp(const char *s1, const char *s2)
{
    while (*s1++ == *s2++ && !*s1);
    if (!*--s1 && !*--s2)return 0;
    return *s1 > *s2 ? 1 : -1;
}

int main(void)
{
    char ch1[] = "hello world";
    char ch2[] = "hallo world";

    // 两个字符串比较
    int value = my_strcmp(ch1, ch2, 5);

    // 返回为1不相等
    printf("%d\n", value);

    return 0;
}
strcmp 使用案例:创建函数

猜你喜欢

转载自www.cnblogs.com/xiangsikai/p/12378533.html
今日推荐