Remove all non-numeric characters from an NSString, keeping spaces

前端 未结 7 731
野性不改
野性不改 2021-01-07 21:57

I am trying to remove all of the non-numeric characters from an NSString, but I also need to keep the spaces. Here is what I have been using.

NS         


        
7条回答
  •  忘掉有多难
    2021-01-07 22:30

    try using NSScanner

    NSString *originalString = @"(123) 123123 abc";
    NSMutableString *strippedString = [NSMutableString 
        stringWithCapacity:originalString.length];
    
    NSScanner *scanner = [NSScanner scannerWithString:originalString];
    NSCharacterSet *numbers = [NSCharacterSet 
        characterSetWithCharactersInString:@"0123456789 "];
    
    while ([scanner isAtEnd] == NO) {
        NSString *buffer;
        if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
            [strippedString appendString:buffer];
        } else {
            [scanner setScanLocation:([scanner scanLocation] + 1)];
        }
    }
    
    NSLog(@"%@", strippedString); // "123123123"
    

提交回复
热议问题