• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

编写一个字符串比较函数my_strcmp,若相等输出0,否则输出两个字符串中第一个不相同字符的ASCII码差值。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
 
int my_strcmp(char a[], char b[])
{
  int i,x;
  char *p1=a,*p2=b;
 
    while (*p1 != '\0' && *p2 != '\0') {
        if (*p1 != *p2) {
            x = *p1 - *p2;
            break;
        }
        p1++;
        p2++;
    }
    if (*p1 == '\0' || *p2 == '\0') {
        x = *p1 - *p2;
    }
    return x;
}
 
void main(void)
{
    char a[100], b[100];
    gets(a);
    gets(b);
    printf("%d\n", my_strcmp(a, b));
}

将第11行指针改成数组

#include <stdio.h>
#include <math.h>
#include <string.h>
 
int my_strcmp(char a[], char b[])
{
  int i,x;
  char *p1=a,*p2=b;
 
    while (*a!= '\0' &&*b != '\0') {
        if (*p1 != *p2) {
            x = *p1 - *p2;
            break;
        }
        p1++;
        p2++;
    }
    if (*p1 == '\0' || *p2 == '\0') {
        x = *p1 - *p2;
    }
    return x;
}
 
void main(void)
{
    char a[100], b[100];
    gets(a);
    gets(b);
    printf("%d\n", my_strcmp(a, b));
}

 

posted on 2022-04-12 20:04  王陈锋  阅读(231)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3