如何编写函数来评估String是否只是字符?

时间:2017-03-21 20:40:39

标签: swift string set character characterview

我已经看到了这个问题的其他答案,但我只想尝试不同的方式。然而,无论我做什么,我都无法使我的类型匹配

func ContainsOnlyAlphabets(_ word : String) -> Bool{
    let letters = CharacterSet.letters // Set<Character>

    let trimmed = word.trimmingCharacters(in: .whitespaces)

    let characterViewArray = Array(trimmed.characters) // Array<characterView>
    let characterArray = characterViewArray.map{Character($0)} // Error: Can't create Chars
    let wordCharactersSet = Set(characterArray) // Set<Character>

    let intersection = wordCharactersSet.intersection(letters)

    return intersection.count == characterArray.count

}

我必须完成所有Set,Char,String,Array转换,但仍然无法正确使用:(。

  

无法为类型&#39;字符&#39;调用初始值设定项带参数列表   类型&#39;((String.CharacterView._Element))&#39;

2 个答案:

答案 0 :(得分:2)

您的代码

let characterViewArray = Array(trimmed.characters)

已经创建了Array<Character>,因此您可以轻松跳过 下一行并使用

创建Set<Character>
let wordCharactersSet = Set(characterViewArray)

但这并没有真正帮助,因为Set<Character>CharacterSet是不同的类型,因此

let intersection = wordCharactersSet.intersection(letters)

无法编译。可能的替代方案是

return trimmed.rangeOfCharacter(from: letters.inverted) == nil

return CharacterSet(charactersIn: trimmed).isSubset(of: letters)

如果您打算同时允许使用字母空白字符 那么它看起来像这样:

func containsOnlyLettersAndWhitespace(_ word : String) -> Bool{
    var allowedSet = CharacterSet.letters
    allowedSet.formUnion(CharacterSet.whitespaces)

    return word.rangeOfCharacter(from: allowedSet.inverted) == nil
    // Alternatively:
    return CharacterSet(charactersIn: word).isSubset(of: allowedSet.inverted)
}

答案 1 :(得分:1)

正如MartinR所说,RewriteEngine On不等同于CharacterSet

我最接近原始解决方案的方法是从修剪过的字符串中创建Set<Character>并将一些原始算法应用于此:

CharacterSet

严格遵守func ContainsOnlyAlphabets(_ word : String) -> Bool{ let letters = CharacterSet.letters let trimmed = word.trimmingCharacters(in: .whitespaces) let wordCharacterSet = CharacterSet(charactersIn:trimmed) let intersection = wordCharacterSet.intersection(letters) return intersection == wordCharacterSet } 领域并对其进行操作,您也可以使用:

CharacterSet

那就是说,我认为我仍然采用马丁的解决方案:

func ContainsOnlyAlphabets(_ word : String) -> Bool{
    return CharacterSet.letters.isSuperset(of:
        CharacterSet(charactersIn: word.trimmingCharacters(in: .whitespaces))
    )
}

更直观。