函數 int stringcompare(char *source, char *target) 比較字符串 source 和 target,並根據 source 是否小於、等於或大於 target 的結果分別返回負整數、0或者整數。該返回值是 source 和 target 由前後逐字符比較時遇到的第一個不相等字符處的字符的差值。
#include <stdio.h>
int stringcompare(char *source, char *target);
int main()
{
char str_a[] = "Welcome to www.bkjia.com";
char str_b[] = "Welcome to www.bkjia.com";
int wait, result;
result = stringcompare(str_b, str_a);
printf("After Function Call: \n");
printf("result is '%d' \n", result);
scanf("%d", &wait);
}
/* 根據 source 按照字典順序小於、等於或大於 target 的結果分別返回負整數、0或者整數 */
int stringcompare(char *source, char *target)
{
int i;
for(i = 0; source[i] == target[i]; i++)
{
if (source[i] == '\0')
return 0;
return source[i] - target[i];
}
}
下面再用指針實現:
int stringcompare(char *source, char *target)
{
for ( ; *source == *target; source++, target++)
if (*source == '\0')
return 0;
return *source - *target;
}
關於指針自增與自減有下面一種用法:
/* 將val壓入棧 */ *p++ = val; /* 將棧頂元素彈出到val中 */ val = *--p;
這兩個表達式是進棧和出棧的標准用法。