【问题标题】:Swift string equalitySwift 字符串相等
【发布时间】:2017-08-06 21:38:06
【问题描述】:

我是 swift 语言的新手,我需要比较一些字符串或任何字符串中的一些字符。

第一个问题: swift的最后一个版本不允许像这样的相等操作==。

if "1" == item.index(item.startIndex, offsetBy: 7){
     print("ok!")
}

item 是一个字符串,它有这个字符串 "01: 06-08-2017, 13:43"(我写 print 的时候可以看到它的内部)

如何检查任何字符串中的某些字符?

【问题讨论】:

  • 好吧,这很快就会让你感到沮丧,但我向你保证,Swift 中的字符串具有当前的实现是有充分理由的(Unicode 兼容性)。尝试阅读Apple's Docs(现在关注“访问和修改字符串”),希望这会让事情更容易掌握。

标签: arrays swift string string-comparison


【解决方案1】:

斯威夫特 3:

为了与一个字符进行比较,您可以简单地通过String.CharacterView实现这一点:

在 Swift 中,每个字符串都提供一个其内容作为字符的视图。 在这种观点中,许多单独的字符——例如,“é”、“김”和 “??”——可以由多个 Unicode 代码点组成。这些代码 点由 Unicode 的边界算法组合成扩展的 字形簇,由 Character 类型表示。的每个元素 CharacterView 集合是 Character 实例。

您可以简单地将其转换为数组并根据其索引检查所需的字符:

let item = "01: 06-08-2017, 13:43"

if "1" == Array(item.characters)[1] {
    print("matched")
}

对于多个字符,您可以生成一个 range 到子字符串:

let item = "01: 06-08-2017, 13:43"

// assuming we will get "06-08-2017"
let range = item.index(item.startIndex, offsetBy: 4) ..< item.index(item.startIndex, offsetBy: 14)

if "06-08-2017" == item.substring(with: range) {
    print("matched")
}

有关子字符串的更多信息,我建议查看this Q&A

【讨论】:

    【解决方案2】:

    您的代码中的错误是item.index(item.startIndex, offsetBy: 7) 的类型不是String,也不是Character。它是 String.Index 类型(在 Swift 3 中,它是 String.CharacterView.Index 的别名),它仅在 String 中占有一个位置,并不代表 String 中的任何内容。

    您有问题的代码将被重写为:

    let item = "01: 06-08-2017, 13:43"
    
    if item[item.index(item.startIndex, offsetBy: 7)] == "1" {
        print("ok!")
    } else {
        print("invalid") //->invalid
    }
    

    您可以使用String.IndexString 下标([]),并在该位置获得Character,并将其与Character 进行比较。 (在这种情况下,"1" 被视为Character,而不是String。)

    String 的下标也适用于 Range&lt;String.Index&gt;

    let startIndex = item.index(item.startIndex, offsetBy: 4)
    let endIndex = item.index(startIndex, offsetBy: 10)
    
    if item[startIndex..<endIndex] == "06-08-2017" {
        print("hit!") //->hit!
    }
    

    在 Swift 4 中,String 类型周围的很多东西都发生了变化,但上面的代码应该在 Swift 3 和 4 中都可以工作。

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多