Objective-C: Find numbers in string

前端 未结 7 1061
遇见更好的自我
遇见更好的自我 2020-11-27 04:37

I have a string that contains words as well as a number. How can I extract that number from the string?

NSString *str = @\"This is my string. #1234\";
         


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-27 05:05

    Self contained solution:

    + (NSString *)extractNumberFromText:(NSString *)text
    {
      NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
      return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
    }
    

    Handles the following cases:

    • @"1234" → @"1234"
    • @"001234" → @"001234"
    • @"leading text get removed 001234" → @"001234"
    • @"001234 trailing text gets removed" → @"001234"
    • @"a0b0c1d2e3f4" → @"001234"

    Hope this helps!

提交回复
热议问题