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

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

    Easily done by creating a character set of characters you want to keep and using invertedSet to create an "all others" set. Then split the string into an array separated by any characters in this set and reassemble the string again. Sounds complicated but very simple to implement:

    NSCharacterSet *setToRemove =   
        [NSCharacterSet characterSetWithCharactersInString:@"0123456789 "];
    NSCharacterSet *setToKeep = [setToRemove invertedSet];
    
    NSString *newString = 
            [[someString componentsSeparatedByCharactersInSet:setToKeep]
                componentsJoinedByString:@""];
    

    result: 333 9599 99

提交回复
热议问题