我有一个NSString,其中包含用户的信用卡号。我想将数字替换为星号。我怎样才能做到这一点?我认为下面的代码不起作用,因为它只针对一个数字:
finalString = [[firstString stringByReplacingOccurancesOfString:@"O" withString:@"*"] stringByReplacingOccurancesOfString:@"o" withString:@"0"];
对所有数字进行for循环是最好的事情,或者有另一种方法吗? TIA!
答案 0 :(得分:4)
这样做:
NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
finalString = [[finalString componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"*"];
答案 1 :(得分:2)
您也可以使用正则表达式执行此类任务: (使用RegExKitLite)
NSString * regex = @"[0-9]";
NSString * stringWithAsteriskInsteadOfNumbers = [stringWithNumbers stringByReplacingOccurrencesOfRegex:regex withString:@"*"];
答案 2 :(得分:0)
最有效的方法,无需分配数以万计的对象:
NSRegularExpression* e = [NSRegularExpression regularExpressionWithPattern:@"\\d"
options:0 error:nil];
finalString = [e stringByReplacingMatchesInString:finalString
options:0
range:NSMakeRange(0, [finalString length])
withTemplate:@"*"];