ios 找出字符串是否为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6091414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:03:24  来源:igfitidea点击:

Finding out whether a string is numeric or not

iphoneobjective-ccocoa-touchiosnsstring

提问by Abhinav

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.

我们如何检查字符串是否仅由数字组成。我正在从字符串中取出一个子字符串,并想检查它是否是数字子字符串。

NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];

回答by John Calsbeek

Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

这是一种不依赖于尝试将字符串解析为数字的有限精度的方法:

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
    // newString consists only of the digits 0 through 9
}

See +[NSCharacterSet decimalDigitCharacterSet]and -[NSString rangeOfCharacterFromSet:].

+[NSCharacterSet decimalDigitCharacterSet]-[NSString rangeOfCharacterFromSet:]

回答by Sam

I'd suggest using the numberFromString:method from the NSNumberFormatterclass, as if the number is not valid, it will return nil; otherwise, it will return you an NSNumber.

我建议使用NSNumberFormatter类中的numberFromString:方法,如果数字无效,它将返回 nil;否则,它会返回一个 NSNumber。

NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
BOOL isDecimal = [nf numberFromString:newString] != nil;

回答by AechoLiu

Validate by regular expression, by pattern "^[0-9]+$", with following method -validateString:withPattern:.

通过正则表达式,通过模式"^[0-9]+$",使用以下方法进行验证-validateString:withPattern:

[self validateString:"12345" withPattern:"^[0-9]+$"];
  1. If "123.123" is considered
    • With pattern "^[0-9]+(.{1}[0-9]+)?$"
  2. If exactly 4 digit numbers, without ".".
    • With pattern "^[0-9]{4}$".
  3. If digit numbers without ".", and the length is between 2 ~ 5.
    • With pattern "^[0-9]{2,5}$".
  4. With minus sign: "^-?\d+$"
  1. 如果考虑“123.123”
    • 带图案 "^[0-9]+(.{1}[0-9]+)?$"
  2. 如果正好是 4 位数字,则没有".".
    • 带图案"^[0-9]{4}$"
  3. 如果数字没有".",长度在 2 ~ 5 之间。
    • 带图案"^[0-9]{2,5}$"
  4. 带减号: "^-?\d+$"

The regular expression can be checked in the online web site.

可以在在线网站上查看正则表达式。

The helper function is as following.

辅助函数如下。

// Validate the input string with the given pattern and
// return the result as a boolean
- (BOOL)validateString:(NSString *)string withPattern:(NSString *)pattern
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSAssert(regex, @"Unable to create regular expression");

    NSRange textRange = NSMakeRange(0, string.length);
    NSRange matchRange = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange];

    BOOL didValidate = NO;

    // Did we find a matching range
    if (matchRange.location != NSNotFound)
        didValidate = YES;

    return didValidate;
}


Swift 3 version:

斯威夫特 3 版本:

Test in playground.

在操场上测试。

import UIKit
import Foundation

func validate(_ str: String, pattern: String) -> Bool {
    if let range = str.range(of: pattern, options: .regularExpression) {
        let result = str.substring(with: range)
        print(result)
        return true
    }
    return false
}

let a = validate("123", pattern: "^-?[0-9]+")
print(a)

回答by Regexident

You could create an NSScanner and simply scan the string:

您可以创建一个 NSScanner 并简单地扫描字符串:

NSDecimal decimalValue;
NSScanner *sc = [NSScanner scannerWithString:newString];
[sc scanDecimal:&decimalValue];
BOOL isDecimal = [sc isAtEnd];

Check out NSScanner's documentationfor more methods to choose from.

查看NSScanner 的文档以获取更多可供选择的方法。

回答by TwoStraws

This original question was about Objective-C, but it was also posted years before Swift was announced. So, if you're coming here from Google and are looking for a solution that uses Swift, here you go:

这个最初的问题是关于 Objective-C 的,但它也是在 Swift 宣布之前几年发布的。因此,如果您从 Google 来到这里并正在寻找使用 Swift 的解决方案,那么您可以:

let testString = "12345"
let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet

if testString.rangeOfCharacterFromSet(badCharacters) == nil {
    print("Test string was a number")
} else {
    print("Test string contained non-digit characters.")
}

回答by Tommy

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.

如果您想完全控制可接受的字符,请使用其他 NSCharacterSet 工厂方法之一。

回答by plamkata__

Swift 3 solution if need to verify that the string has only digits:

如果需要验证字符串是否只有数字,则使用 Swift 3 解决方案:

CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))

回答by hhamm

Swift 3 solution could be like:

Swift 3 解决方案可能是这样的:

extension String {

    var doubleValue:Double? {
        return NumberFormatter().number(from:self)?.doubleValue
    }

    var integerValue:Int? {
        return NumberFormatter().number(from:self)?.intValue
    }

    var isNumber:Bool {
        get {
            let badCharacters = NSCharacterSet.decimalDigits.inverted
            return (self.rangeOfCharacter(from: badCharacters) == nil)
        }
    }
}

回答by MrTristan

to be clear, this functions for integers in strings.

需要明确的是,这个函数用于字符串中的整数。

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

继承人基于上面约翰的回答一个小帮手类别:

in .h file

在 .h 文件中

@interface NSString (NumberChecking)

+(bool)isNumber:(NSString *)string;

@end

in .m file

在 .m 文件中

#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");
}

回答by ravron

John Calsbeek's answeris nearly correct but omits some Unicode edge cases.

John Calsbeek 的回答几乎是正确的,但省略了一些 Unicode 边缘情况。

Per the documentation for decimalDigitCharacterSet, that set includes all characters categorized by Unicode as Nd. Thus their answer will accept, among others:

根据 的文档decimalDigitCharacterSet,该集合包括所有被 Unicode 归类为 的字符Nd。因此,他们的回答将接受,其中包括:

  • ?(U+0967 DEVANAGARI DIGIT ONE)
  • ?(U+1811 MONGOLIAN DIGIT ONE)
  • (U+1D7D9 MATHEMATICAL DOUBLE-STRUCK DIGIT ONE)
  • ?(U+0967 梵文数字一)
  • ?(U+1811 蒙古语数字一)
  • (U+1D7D9 数学双击数字一)

While in some sense this is correct — each character in Nddoes map to a decimal digit — it's almost certainly not what the asker expected. As of this writing there are 610 code points categorized as Nd, only ten of which are the expected characters 0(U+0030) through 9(U+0039).

虽然从某种意义上说这是正确的 - 中的每个字符Nd都映射到一个十进制数字 - 这几乎肯定不是提问者所期望的。在撰写本文时,有610 个代码点被归类为Nd,其中只有 10 个是预期的字符0(U+0030) 到9(U+0039)。

To fix the issue, simply specify exactly those characters that are acceptable:

要解决此问题,只需准确指定可接受的字符:

NSCharacterSet* notDigits = 
    [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
    // newString consists only of the digits 0 through 9
}