【问题标题】:Replace numbers with an asterisk in Objective-C在 Objective-C 中用星号替换数字
【发布时间】:2012-09-25 07:12:30
【问题描述】:

我有一个包含用户信用卡号的 NSString。我想将数字替换为星号。我怎样才能做到这一点?我认为下面的代码行不通,因为它只针对一个数字:

finalString = [[firstString stringByReplacingOccurancesOfString:@"O" withString:@"*"] stringByReplacingOccurancesOfString:@"o" withString:@"0"];

对所有数字执行 for 循环是最好的做法还是有其他方法?蒂亚!

【问题讨论】:

    标签: objective-c xcode replace nsstring character


    【解决方案1】:

    这样做:

    NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
     finalString = [[finalString componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"*"];
    

    【讨论】:

    • 如果我只想替换16位卡号的前12个字符怎么办?
    【解决方案2】:

    您也可以对此类任务使用正则表达式: (使用 RegExKitLite)

     NSString * regex = @"[0-9]";
     NSString * stringWithAsteriskInsteadOfNumbers = [stringWithNumbers stringByReplacingOccurrencesOfRegex:regex withString:@"*"];
    

    【讨论】:

    • 没有stringByReplacingOccurrencesOfRegex 这样的东西。 xcode 无法识别。可能是...... 9年前
    【解决方案3】:

    最有效的方式,无需分配无数对象:

    NSRegularExpression* e = [NSRegularExpression regularExpressionWithPattern:@"\\d" 
                                 options:0 error:nil];
    finalString = [e stringByReplacingMatchesInString:finalString
                                              options:0 
                                                range:NSMakeRange(0, [finalString length]) 
                                         withTemplate:@"*"];
    

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多