1. 程式人生 > >int strncasecmp(const char *s1, const char *s2, size_t n)的實現

int strncasecmp(const char *s1, const char *s2, size_t n)的實現

函式定義:int strncasecmp(const char *s1, const char *s2, size_t n);
函式說明:strncasecmp()用來比較引數s1 和s2 字串前n個字元,比較時會自動忽略大小寫的差異。
返回值:若引數s1 和s2 字串相同則返回0。s1 若大於s2 則返回大於0 的值,s1 若小於s2 則返回小於0 的值。
注:為了用系統的strncasecmp函式進行驗證,將自己實現的strncasecmp重新命名為src_strncasecmp

#include <string>
#include <iostream>
using namespace std;

int src_strncasecmp(const char *s1, const char *s2, size_t n)
{
	int c1 = 0, c2 = 0;
	while(n--)
	{
		c1 = *s1++;
		c2 = *s2++;
		if(!c1 || !c2) break;
		if(c1>='A'&&c1<='Z') c1 += 'a' - 'A';
		if(c2>='A'&&c2<='Z') c2 += 'a' - 'A';
		if(c1!=c2) break;
	}
	return c1-c2;
}

int main(int argc,char* argv)
{
    char *a = "aBcDeF";
    char *b = "AbC";
	cout << "system function:";
    if(!strncasecmp(a, b, 4)) cout << a << " = " << b << endl;
	else cout << a << " != " << b << endl;
	cout << "own function:";
	if(!src_strncasecmp(a, b, 4)) cout << a << " = " << b << endl;
	else cout << a << " != " << b << endl;
	return 0;
}

用多個字串進行測試,自定義的strncasecmp函式和系統的strncasecmp函式輸出相同,說明自定義的strncasecmp函式是正確的。