Finding out whether a string is numeric or not

前端 未结 18 1715
一个人的身影
一个人的身影 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条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 16:07

    I think the easiest way to check that every character within a given string is numeric is probably:

    NSString *trimmedString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    
    if([trimmedString length])
    {
        NSLog(@"some characters outside of the decimal character set found");
    }
    else
    {
        NSLog(@"all characters were in the decimal character set");
    }
    

    Use one of the other NSCharacterSet factory methods if you want complete control over acceptable characters.

提交回复
热议问题