zoukankan      html  css  js  c++  java
  • 字符串函数---strcmp()与strncmp()具体解释及实现

    一、strcmp()与strncmp()


           strcmp():strcmp(s1,s2);            比較两个字符串。
           strncmp():strncmp(s1,s2);       比較两个字符串前n位

           比較规则:从左到右逐个字符进行比較(ASCII值),直到出现不同的字符或遇到''为止。
           假设所有的字符同样。则觉得两字符串相等,返回值为0。
           假设出现不同的字符,则对第一次出现不同的字符进行比較。比較方法是以s1的第一个不同的字符减去s2的第一个不同的字符。以所得差值作为返回值(大于0。则返回1,小于0则返回-1)。


    代码实例:

    #include<iostream>
    #include<assert.h>
    using namespace std;
    
    int main()
    {
    	char a[]="aaaae";
    	char b[]="aaaaf";
    
    	int i=strcmp(a,b);
    
    	cout<<i<<endl;
    
    	int j=strncmp(a,b,4);//仅仅比較前n个字符
    
    	cout<<j<<endl;
    
    
    	system("pause");
    	return 0;
    }
    执行结果为 -1。0。


    二、strcmp()与strncmp()的详细实现

    #include<iostream>
    #include<assert.h>
    using namespace std;
    
    int strcmp_m(const char *s1,const char *s2)
    {
    	assert((s1!=NULL)&&(s2!=NULL));
    
    	while(*s1!=''&&*s2!='')//字符串前面部分都同样
    	{
    		if(*s1-*s2>0)
    			return 1;
    		if(*s1-*s2<0)
    			return -1;
    		s1++;
    		s2++;
    	}
    	if(*s1==''&&*s2!='')//谁先为'',谁就小
    		return -1;
    	if(*s2==''&&*s1!='')
    		return 1;
    	return 0;              //同一时候为''     
    }
    
    int strncmp_m(const char *s1,const char *s2,int n)
    {
    	assert((s1!=NULL)&&(s2!=NULL));
    
    	while(*s1!=''&&*s2!=''&&n)//字符串前面部分都同样
    	{
    		if(*s1-*s2>0)
    			return 1;
    		if(*s1-*s2<0)
    			return -1;
    		s1++;
    		s2++;
    		n--;
    	}
    	if(*s1==''&&*s2!='')//谁先为'',谁就小
    		return -1;
    	if(*s2==''&&*s1!='')
    		return 1;
    	return 0;              //同一时候为''  
    }
    
    int main()
    {
    	char a[]="aaaae";
    	char b[]="aaaaf";
    
    	int i=strcmp_m(a,b);
    
    	cout<<i<<endl;
    
    	int j=strncmp_m(a,b,4);//仅仅比較前n个字符
    
    	cout<<j<<endl;
    
    
    	system("pause");
    	return 0;
    }

    执行结果为 -1,0。实现了strcmp()函数与strncmp()函数的功能。



  • 相关阅读:
    e3.tree参考手册
    fckeditor使用详解
    提示constructor无法location的原因
    无限联动下拉框使用步骤
    动态sql构建的过程
    xsqlbuilder使用说明
    处理date类型对象的方式
    wdatepicker使用指南
    How to reclaim space in InnoDB when innodb_file_per_table is ON
    Bash script: report largest InnoDB files
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/6811752.html
Copyright © 2011-2022 走看看