您好,登錄后才能下訂單哦!
小編給大家分享一下基于Luhn算法格式校驗用戶輸入的銀行卡號是否正確,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
iOS代碼:
/** * 銀行卡格式校驗 * * @param cardNo 銀行卡號 * * @return */ + (BOOL) checkCardNo:(NSString*) cardNo{ int oddsum = 0; //奇數求和 int evensum = 0; //偶數求和 int allsum = 0; int cardNoLength = (int)[cardNo length]; int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue]; cardNo = [cardNo substringToIndex:cardNoLength - 1]; for (int i = cardNoLength -1 ; i>=1;i--) { NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)]; int tmpVal = [tmpString intValue]; if (cardNoLength % 2 ==1 ) { if((i % 2) == 0){ tmpVal *= 2; if(tmpVal>=10) tmpVal -= 9; evensum += tmpVal; }else{ oddsum += tmpVal; } }else{ if((i % 2) == 1){ tmpVal *= 2; if(tmpVal>=10) tmpVal -= 9; evensum += tmpVal; }else{ oddsum += tmpVal; } } } allsum = oddsum + evensum; allsum += lastNum; if((allsum % 10) == 0) return YES; else return NO; }
Androd代碼:
/** * 匹配Luhn算法:可用于檢測銀行卡卡號 * @param cardNo * @return */ public static boolean matchLuhn(String cardNo) { int[] cardNoArr = new int[cardNo.length()]; for (int i=0; i<cardNo.length(); i++) { cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i))); } for(int i=cardNoArr.length-2;i>=0;i-=2) { cardNoArr[i] <<= 1; cardNoArr[i] = cardNoArr[i]/10 + cardNoArr[i]%10; } int sum = 0; for(int i=0;i<cardNoArr.length;i++) { sum += cardNoArr[i]; } return sum % 10 == 0; }
附(銀行卡號格式化):
在輸入銀行卡號過程中,通常,我們會每隔4位插入一個"-",類似"1332-2131-2313-1231-212"這種的格式
可以通過以下方法實現:
設置textField的代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *text = [textField text]; NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"]; string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""]; if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) { return NO; } text = [text stringByReplacingCharactersInRange:range withString:string]; text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""]; NSString *newString = @""; while (text.length > 0) { NSString *subString = [text substringToIndex:MIN(text.length, 4)]; newString = [newString stringByAppendingString:subString]; if (subString.length == 4) { newString = [newString stringByAppendingString:@"-"]; } text = [text substringFromIndex:MIN(text.length, 4)]; } newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]]; if (newString.length >= 24) { return NO; } [textField setText:newString]; return NO; }
最后,怎么獲得不包含符號"-"的銀行卡號呢?
[self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""]
看完了這篇文章,相信你對“基于Luhn算法格式校驗用戶輸入的銀行卡號是否正確”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。