MENU

字符串的比较(二)

• October 31, 2020 • 串和数组

编写算法实现字符串str1和str2的比较操作,要求比较结果包括大于、小于或等于三种情况


题目分析:

咱们看看字符串的比较(一),题目区别不大,要求输出三种结果,思路我就不再赘述了,直接上代码

代码实现:

#include<stdio.h>
#include<stdlib.h>
/*字符串比较函数,相同返0,str1>str2返1,否则返-1*/
int strcompare(char str1[], char str2[])
{
    int size1 = 0, size2 = 0;             //用来累计字符ascll码之和
    for (int i = 0; str1[i] != '\0'; i++)
        size1 += (int)str1[i];            //加上字符的(int)即ascll码
    for (int i = 0; str2[i] != '\0'; i++)
        size2 += (int)str2[i];
    if (size1 == size2)                   //字符串大小一样
        return 0;
    else if (size1 > size2)
        return 1;
    else
        return -1;
}
int main()
{
    char str1[] = "aseff";
    char str2[] = "assff";
    char str3[] = "aesff";
    if (strcompare(str1, str2)==0)         //比较str1和str2
        printf("%s和%s相同!\n",str1,str2);
    else if(strcompare(str1,str2)==-1)
        printf("%s小于%s\n", str1, str2);
    else
        printf("%s大于%s\n", str1, str2);
    if (strcompare(str1, str3) == 0)         //比较str1和str3
        printf("%s和%s相同!\n", str1, str3);
    else if (strcompare(str1, str3) == -1)
        printf("%s小于%s\n", str1, str3);
    else
        printf("%s大于%s\n", str1, str3);
    system("pause");
    return 0;
}

运行结果:


img



代码编译器:Visual Studio 2017
ok,再见

Archives QR Code Tip
QR Code for this page
Tipping QR Code