【问题标题】:Swift: Compare the first character of stringSwift:比较字符串的第一个字符
【发布时间】:2016-06-30 20:36:34
【问题描述】:

如何比较字符串的第一个字符和 Swift 中的字符?例如:

伪代码:

str = "my name is John"

if str[0] == m {
} 

【问题讨论】:

  • 拼写为“伪代码”

标签: swift string nsstring


【解决方案1】:
let s = "abcd"

if s.hasPrefix("a") {  // takes a String or a literal
}

if s.first == "a" {  // takes a Character or a literal
}

if s[s.startIndex] == "a" { // takes a Character or a literal
}

【讨论】:

    【解决方案2】:

    这适用于 Swift 3 中的任何字符比较:

        var str: String = "abcd"    
    
        if str[str.index(str.startIndex, offsetBy: i)] == "a" {
    
        }
    

    在哪里, i = 使用字符串的任何索引值 在上面的例子中它是 0 i = 0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多