第16周项目2-比较字符串

来源:互联网 发布:淘宝上我的店铺去哪找 编辑:程序博客网 时间:2024/06/01 19:28
/  *copyright (c)2014,烟台大学计算机学院  *All rights reserved  *文件名称:123.cpp  *作者:孙春红  *完成日期:2014年12月15日  *版本号:v1.0  *  *问题描述:编写程序,比较字符串。  *输入描述:略。  *程序输出:如果字符串1大于字符串2,输出1;如果字符串1等于字符串2,输出0;如果字符串1小于字符串2,输出-1。  */  #include <iostream>using namespace std;int pstrcmp( const char *str1,const char *str2);int main(){    char s1[50]="I'm a vegetable bird ";    char s2[50]="I'm a shy person";    cout<<"句子为:"<<endl;    cout<<s1<<endl;    cout<<s2<<endl;    cout<<endl;    cout<<"比较的结果:"<<endl;    cout<<pstrcmp(s1,s2)<<endl;    return 0;}int pstrcmp(const char *str1,const char *str2){    int i=0;    while(*(str1+i)==*(str2+i)&&*(str1+i)!='\0'&&*(str2+i)!='\0')        i++;    if(*(str1+i)>*(str2+i))        return 1;    else if(*(str1+i)<*(str2+i))        return -1;    else return 0;}


运行结果:

知识点总结:

学会运用指针做形参编写程序,比较字符串的长度。还有在调用函数时要用int型,不能用char型,因为字符串的比较需要用到ASULL值,而ASCLL值必须使用int型,否则会出现error。

0 0
原创粉丝点击