Chinaunix首页 | 论坛 | 博客
  • 博客访问: 112656
  • 博文数量: 29
  • 博客积分: 1440
  • 博客等级: 上尉
  • 技术积分: 371
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-03 15:57
文章分类

全部博文(29)

文章存档

2011年(5)

2010年(1)

2009年(23)

我的朋友

分类: C/C++

2009-12-08 11:39:03

今天认真的学习了字符串比较函数 strcmp
 
原型:    int strcmp(char *s1, char *s2);
头文件:  include
返回值:  返回 int 整型值
strcmp对两串从左向右逐个字符比较(ASCII码),直到遇到不同字符或'\0'为止。若s1大于s2返回正整数,若s1小于s2返回负整数,若s1等于s2返回0。要注意字符串比较不能用"==",必须用strcmp。

#include 

#include 

typedef struct

{

    char name[20];

    char num[20];

}USERINFO;

main()

{

    USERINFO user;

    char newname[ ]="Rose";

    int result;

    strcpy(user.name,"Mike");

    result=strcmp(user.name,newname);

    if(result!=0)

        printf("different person!");

    else

        Printf("the same person!");

 

自己动手写程序,实现strcmp()函数的功能。

#include
#include
#include
#define SIZE 1024
int str_cmp(char s1[],char s2[]);
int main()
{
 char a[SIZE]={0};
 char b[SIZE]={0};
 printf("please input the first string:");
 gets(a);
 printf("please input the second string:");
 gets(b);
 if(str_cmp(a,b) == 0)
 {
  printf("the two strings are same!");
 }else{
  printf("error inputs!");
 }
 return 0;
}
 
int str_cmp(char s1[],char s2[])
{
 int i,j;
 i=0;
 j=0;
 while((i < strlen(s1))&&(j < strlen(s2)))
 {
  if(s1[i] == s2[j])
  {
   i++;
   j++;
  }else{
   return s1[i]-s2[j];
  }
  
 }
 if((i== strlen(s1))&&(j == strlen(s2)))
  return 0;
 else
  return -1;
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
阅读(3458) | 评论(0) | 转发(0) |
0

上一篇:自己的命运自己做主

下一篇:怅然若失

给主人留下些什么吧!~~