如何检查字符串是否包含空格/字母数字/等字符? [英] How can I check to see if a string contains characters of whitespace/alphanumeric/etc?

查看:215
本文介绍了如何检查字符串是否包含空格/字母数字/等字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Swift中的ctype.h库来使用 isAlpha isSpace 在人物?或者有更好的Swift方式吗?

How can you use the "ctype.h" library in Swift to be able to use isAlpha or isSpace on characters? Or is there a better, Swift, way of doing it?

这个问题已得到解答,但它似乎不起作用:
Swift:如何确定字母是字母数字还是数字

This question is answered, but it doesn't seem to work: Swift: how to find out if letter is Alphanumeric or Digit

它没有指定如何导入库。有人能指出我正确的方向吗?

It doesn't specify how to import the library. Could someone point me in the right direction?

这是我到目前为止所得到的:

Here's what I've got so far:

extension String {
    subscript (i : Int) -> String {
        return String(Array(self)[i])
    }
}

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"

for var i=0; i<countElements(phrase); i++ {
    if whitespace.characterIsMember(phrase[i]) { //error
        println("char is whitespace")
    }
}


推荐答案

对整个字符串使用NSCharacter,而不是逐个字符:

Use NSCharacter on the entire string,not character-by-character:

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(whitespace)

// range will be nil if no whitespace is found
if let test = range {
    println("whitespace found")
}
else {
    println("whitespace not found")
}

输出:

whitespace found

这篇关于如何检查字符串是否包含空格/字母数字/等字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆