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

前端 未结 7 648
野性不改
野性不改 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:38

    In brief, you can use NSCharacterSet to examine only those chars that are interesting to you and ignore the rest.

    - (void) stripper {
    
        NSString *inString = @"A1 B2 C3 D4";
        NSString *outString = @"";
    
        for (int i = 0; i < inString.length; i++) {
    
            if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:[inString characterAtIndex:i]] || [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[inString characterAtIndex:i]]) {
    
                outString = [outString stringByAppendingString:[NSString stringWithFormat:@"%c",[inString characterAtIndex:i]]];
            }
        }
    }
    

提交回复
热议问题