Zero0_18 2021-05-28 11:06 采纳率: 50%
浏览 167
已采纳

一个C语言问题,用一个函数实现两个字符串的比较。

用一个函数实现两个字符串的比较,即自己写一个strcmp函数,函数原型为:
int strcmp(char *p1,char *p2);

要求:

两个串相等时,返回0
p1>p2时,返回值>0
p1<p2时,返回值<0

请求一个流程图,还有最后实际测试效果,两个串分别三种情况下最后显示是怎么样的。

谢谢大佬们了!

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2021-05-28 11:55
    关注

    供参考:

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int My_strcmp(char *str1,char *str2)    //声明两个字符指针变量str1和str2
    {
        while(*str1 == *str2 && *str1!='\0')
        {
              str1++;
              str2++; 
        }
        if(*str1 == '\0' && *str2 == '\0') return 0;
        else  return  (*str1-*str2);// 返回字符串比较结果
    }
    
    
    int main()
    {
        char s1[50], s2[50];
        int r;
        cout<<"please input the first string: ";
        cin>>s1;
        cout<<"please input the second string: ";
        cin>>s2;
        r=My_strcmp(s1,s2);
        cout<<r<<endl;
        if (r>0)
            cout<<s1<<" is larger!"<<endl;
        else  if (r<0)
            cout<<s2<<" is larger"<<endl;
        else
            cout<<s1<<" and "<<s2<<" is eqaul"<<endl;
        
        return 0;
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”