//:Vc++6.0 String strncmp函數
//功能:指定大小比較字符串
//參數:str1 字符串1 str2 字符串2 num 比較個數
//返回值:正確返回其差值 錯誤返回 -65535
#include<stdio.h>
int strncmp(const char *str1, const char *str2, int num);
int main()
{
char str[][5] = {"R2D2", "C3PO", "R2A6"};
int n;
printf("Looking for R2 astromech droids...\n");
for (n=0 ; n<3 ; n++)
if (strncmp(str[n],"R2xx",2) == 0) //比較字符串中前兩個字符為“R2”
{
printf("found %s\n",str[n]);
}
return 0;
}
int strncmp(const char *str1, const char *str2, int num)
{
//查錯
if (str1 == NULL || str2 == NULL)
{
perror("str1 or str2");
return -65535;
}
if (num <= 0)
{
perror("num");
return -65535;
}
//求字符串長度
int len1, len2;
const char *temp1 = str1;
const char *temp2 = str2;
while (*(temp1++) != '\0');
len1 = temp1 - str1;
while (*(temp2++) != '\0');
len2 = temp2 - str2;
//比較
if (num >= len1 && num >= len2)
{
while (*str1 != '\0' || *str2 != '\0')
{
if (*str1 != *str2)
{
return *str1 - *str2;
}
else
{
str1++;
str2++;
}
}
if (*str1 == '\0' && *str2 == '\0')
return 0;
if (*str1 != '\0' && *str2 == '\0')
return *str1;
if (*str1 == '\0' && *str2 != '\0')
return -*str2;
}
else
{
int i;
for (i = 0; i < num; i++)
{
if (*str1 == '\0' || *str2 == '\0')
break;
if (*str1 != *str2)
{
return *str1 - *str2;
}
else
{
str1++;
str2++;
}
}
if (i >= num)
return 0;
if (*str1 != '\0' && *str2 == '\0')
return *str1;
if (*str1 == '\0' && *str2 != '\0')
return -*str2;
}
}
//在vc++6.0中的運行結果為: Looking for R2 astromech droids...
// found R2D2
// found R2A6 //:~
|