Swift字符串相等

时间:2017-08-06 21:38:06

标签: arrays swift string string-comparison

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

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

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

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

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

2 个答案:

答案 0 :(得分:1)

斯威夫特3:

要与一个角色进行比较,您只需String.CharacterView

即可实现此目的
  

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

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

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

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

对于更多这一个字符,您可以为子字符串生成范围

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

答案 1 :(得分:1)

代码中的错误是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
}

您可以使用[]下标StringString.Index并在该位置获得Character,并将其与Character进行比较。 (在此上下文中,"1"被视为Character,而不是String。)

String的下标也适用于Range<String.Index>

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&amp; 4。