【C++】 应用指针,编写一个函数strcmp()实现两个字符串s1和s2的比较。如果s1=s2,则返回值为0,如果s1不等于s2,返回它们两者第一个不同的字符的ASC II码差值,并且若s1>s2,

2023-11-08

#include<iostream>  
using namespace std;
int strlen(char str)
{
    int i=0, len = 0;
    while (str != '/0')
    {
        len++;
        i++;
    }
    return len;
}
int strcmp(char str1[], char str2[], int lenth)
{
    int i;
    char* p1,*p2;
    p1 = str1;
    p2 = str2;
    for ( i = 0; i < lenth; i++)
    {
        if (*(p1+i) != *(p2+i))
            break;
    }
    if (i == lenth - 1)
        return 0;
    else
        return((int)*(p1 + i)) - ((int)*(p2 + i));
}
int main()
{
    int lenth = 0;
    char str1[30] ;
    char str2[30];
    cout << "请输入字符串1和字符串2" << endl;
    cin >> str1 >> str2;
    if(strlen(str1)<strlen(str2))
        lenth= strlen(str1);
    else
        lenth= strlen(str2);
    if (strcmp(str1, str2, lenth) == 0)
        cout << "返回值为0" << endl;
    else
        if (strcmp(str1, str2, lenth) > 0)
           
            cout << "返回值为1" << endl;
        else
            cout << "返回值为-1" << endl;
    return 0;
}

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【C++】 应用指针,编写一个函数strcmp()实现两个字符串s1和s2的比较。如果s1=s2,则返回值为0,如果s1不等于s2,返回它们两者第一个不同的字符的ASC II码差值,并且若s1>s2, 的相关文章

随机推荐