ios 如何检查文本是否只包含数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34587094/
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-31 08:31:01  来源:igfitidea点击:

How to check if text contains only numbers?

iosswift

提问by Luca Angeletti

I've tried many cases, but none work for me. I tried:

我尝试了很多情况,但没有一个对我有用。我试过:

if resultTitles[indexPath.row].rangeOfCharacterFromSet(badCharacters) == nil {
    let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    print("Index: \(indexPath.row)")
}

also tried to

也试图

if ((resultTitles[0].toInt()) != nil) {
    print("ERROR")
}

So, how can I check that my text contains only numbers?

那么,如何检查我的文本是否只包含数字?

回答by Cristina De Rito

I find this solution, in Swift 3, to be cleaner

我发现这个解决方案,在 Swift 3 中,更干净

import Foundation

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

回答by Luca Angeletti

You just need to check whether the Setof the characters of your Stringis subsetof the Setcontaining the characters from 0 to 9.

你只需要检查是否Set你的角色String子集Set包含字符从0到9。

extension String {
    var isNumeric: Bool {
        guard self.characters.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self.characters).isSubset(of: nums)
    }
}

"".isNumeric // false
"No numbers here".isNumeric // false
"123".isNumeric // true
"Hello world 123".isNumeric // false

回答by Brandon A

Expanding on the fantastic work from Luca above, here is the answer given written by way of Swift 5.

扩展上面 Luca 的出色工作,这里是通过 Swift 5 给出的答案。

extension String {
    var isNumeric: Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}

回答by technerd

This may help you.

这可能对你有帮助。

 let string  = "536783"
    let num = Int(string);

    if num != nil {
        print("Valid Integer")   
    }
    else {
        print("Not Valid Integer")
    }

回答by Manuel

Try with this

试试这个

let numbersTest = resultTitles[indexPath.row]
        if let number = Int(numbersTest){
            print(number)//contains onlyy number
        }else{
            print("notnumber")//Not number
        }

回答by Blair McArthur

It depends what you mean by numbers. If you mean 0-9 then you can use this:

这取决于你所说的数字是什么意思。如果你的意思是 0-9 那么你可以使用这个:

let numbersSet = CharacterSet(charactersIn: "0123456789")

let textCharacterSet = CharacterSet(charactersIn: "123")

if textCharacterSet.isSubset(of: numbersSet) {
    print("text only contains numbers 0-9")
} else {
    print("text contains invalid characters")
}

If you mean all kinds of different ways of specifying numbers then you can use CharacterSet.decimalDigits which contains all kinds of ways of specifying numbers.

如果您指的是各种不同的数字指定方式,那么您可以使用 CharacterSet.decimalDigits,其中包含各种指定数字的方式。

回答by Hussein

Some of the codes above will work only with Arabic Digits ( 0, 1 , 2 ,...). However, it won't work with other digits format ( like Hindi one which is used in Arabic countries, ?, ? , ? , or that one used in Chinese ..)

上面的一些代码仅适用于阿拉伯数字( 0, 1 , 2 ,...)。但是,它不适用于其他数字格式(例如在阿拉伯国家使用的印地语格式,?, ? , ? 或在中文中使用的那种..)

I have tested the below code ( taken from the codes above with some correction for is Digits with different numbers format ( Chinese, Hindi used in Arabic , ...).

我已经测试了下面的代码(取自上面的代码,并对具有不同数字格式的数字进行了一些更正(中文,阿拉伯语中使用的印地语,......)。

extension String {

    var isNumeric : Bool { return CharacterSet(charactersIn: self).isSubset(of: CharacterSet.decimalDigits)
    }

    var isDigits : Bool {
        guard !self.isEmpty else { return false }
        let containsNonNumbers = self.contains { !
var arr_IsStringNumberOnly:[String] = ["123", "456.7", "890,1", "1'234", "", "abc", "def3", "xyz 4", "5 ??ü"]
for i in 0..<arr_IsStringNumberOnly.count {
    //the code w/o 'nil'
    CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i]))

    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "abc")) //if empty assume it's text

    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "123")) //if empty assume it's numeric


    //presentation:
    print("arr_IsStringNumberOnly[i]: \(arr_IsStringNumberOnly[i]) \t '\(CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i])) )'")

}
.isNumber } return !containsNonNumbers } }

回答by RvdH

based on 'Cristina De Rito' solution here is a little playgrud routine for checking results, you can add your own CharacterSet(swift 5)

基于'Cristina De Rito'解决方案,这里有一个检查结果的小游戏例程,您可以添加自己的CharacterSet(swift 5)

extension String {
  var isDigits: Bool {
    guard !self.isEmpty else { return false }
    return !self.contains { Int(String(
func isStringContainsOnlyNumbers(string: String) -> Bool {
    return string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil
}

// Now let's try to use it

let str = "Hello, playground"

if (isStringContainsOnlyNumbers(str)) {
    print("\(str) has illegal characters")  // "Hello, playground has illegal characters"
}
else {
    print("\(str) has only number")
}

let numStr = "332432"

if (isStringContainsOnlyNumbers(numStr)) {
    print("\(numStr) has illegal characters")
}
else {
    print("\(numStr) has only number")   // "332432 has only number\n"
}
)) == nil } } } "123".isDigits // returns true "12d".isDigits // returns false

Presents:

礼物:

  • arr_IsStringNumberOnly[i]: 123 'true'
  • arr_IsStringNumberOnly[i]: 456.7 'true'
  • arr_IsStringNumberOnly[i]: 890,1 'true'
  • arr_IsStringNumberOnly[i]: 1'234 'true'
  • arr_IsStringNumberOnly[i]: 'true'
  • arr_IsStringNumberOnly[i]: abc 'false'
  • arr_IsStringNumberOnly[i]: def3 'false'
  • arr_IsStringNumberOnly[i]: xyz 4 'false'
  • arr_IsStringNumberOnly[i]: 5 ??ü 'false'
  • arr_IsStringNumberOnly[i]: 123 '真'
  • arr_IsStringNumberOnly[i]: 456.7 '真'
  • arr_IsStringNumberOnly[i]: 890,1 '真'
  • arr_IsStringNumberOnly[i]: 1'234 '真'
  • arr_IsStringNumberOnly[i]: '真'
  • arr_IsStringNumberOnly[i]: abc 'false'
  • arr_IsStringNumberOnly[i]: def3 'false'
  • arr_IsStringNumberOnly[i]: xyz 4 'false'
  • arr_IsStringNumberOnly[i]: 5 ??ü 'false'

回答by Firas Safa

The cleanest Swiftway in my opinion is this:

Swift在我看来,最干净的方法是这样的:

##代码##

回答by Ossir

Your first options works for me in playground. Check it again. Assuming str = resultTitles[indexPath.row]

你的第一个选择在操场上对我有用。再检查一下。假设str = resultTitles[indexPath.row]

##代码##