@interface Utility : NSObject { } //验证身份证是否有效 + (BOOL)checkIDCard:(NSString *)str; @end
@interface Utility () int checkIDfromchar (const char *sPaperId); @end @implementation Utility //验证身份证是否有效 int checkIDfromchar (const char *sPaperId) { long lSumQT =0; int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; //加权因子 char sChecker[11]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'}; //校验码 if( 18 != strlen(sPaperId)) return 0; //检验长度 //校验数字 for (int i=0; i<18; i++){ if ( !isdigit(sPaperId[i]) && !(('X' == sPaperId[i] || 'x' == sPaperId[i]) && 17 == i) ) { return 0; } } //验证最末的校验码 for (int i=0; i<=16; i++) { lSumQT += (sPaperId[i]-48) * R[i]; } if (sChecker[lSumQT%11] != sPaperId[17] ){ return 0; } return 1; } + (BOOL)checkIDCard:(NSString *)str{ return checkIDfromchar((char *)[str UTF8String]); } @end
支持最后一位为X