Finding out whether a string is numeric or not

前端 未结 18 1670
一个人的身影
一个人的身影 2020-12-07 15:24

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSS         


        
18条回答
  •  Happy的楠姐
    2020-12-07 15:51

    to be clear, this functions for integers in strings.

    heres a little helper category based off of John's answer above:

    in .h file

    @interface NSString (NumberChecking)
    
    +(bool)isNumber:(NSString *)string;
    
    @end
    

    in .m file

    #import "NSString+NumberChecking.h"
    
    @implementation NSString (NumberChecking)
    
    +(bool)isNumber {
        if([self rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound) {
            return YES;
        }else {
            return NO;
        }
    }
    
    @end
    

    usage:

    #import "NSString+NumberChecking.h"
    
    if([someString isNumber]) {
        NSLog(@"is a number");
    }else {
        NSLog(@"not a number");
    }
    

提交回复
热议问题