【问题标题】:How do I get the index of a multi-line string literal in Swift如何在 Swift 中获取多行字符串文字的索引
【发布时间】:2017-12-31 19:48:13
【问题描述】:

我正在尝试查找与指定值匹配的字符串的索引。一种方法是使用实​​例方法,但这假设我正在使用数组;我正在使用多行字符串文字。关于这个主题的大部分documentation 都涉及制作 Swift 中具有预定义 值的多行字符串文字。

假设我有以下多行字符串文字:

"""
Product 1 description
Product 1 color
Product 2 description
Product 2 color
"""

我想定义两个变量:一个用于检查全局变量是否与上面列表中的字符串匹配,第二个用作索引。例如:

[In]  [1]: let keyword = "Product 2 description"
[In]  [2]: if keyword in multi-line string literal {
              print(index of match as integer)
           }
[Out] [3]: 2

通过使用Levenshtein distance 计算器来查找和定义匹配项,我已经成功地完成了程序中的第一个变量,但是我在完成第二个变量时遇到了麻烦。我尝试拆分列表并制作元组,但是当我在列表上enumerated() 时,每个字符串都会产生0 的索引。也就是说,如果有人可以在以下方面帮助我任何,我将不胜感激:

  • 获取上述多行字符串字面量的索引值
  • 定义一个计数变量,其值是一个整数,每次字符串迭代都会改变
  • 将上面的多行字符串文字转换成一个列表,每个字符串都有一个索引

【问题讨论】:

  • 将您的 多行文字 转换为 [String]let arr = mll.split(separator: "\n")
  • 这适用于大多数字符串,但不适用于我的多行文字中的那些 - 它们包含特殊字符,因此上面的代码将每个字符串转换为自己的列表项(即["Product 1 description"]\n["Product 1 color"]]\n["Product 2 description"]\n["Product 2 color"])。不过还是谢谢!
  • @LeoDabus 我尝试了一位用户在该线程中提出的三种解决方案——componentsSeparatedByCharactersInSetsplitenumerateLines——但我的输出没有改变;我不断将每个字符串作为其自己的列表项。也许这是因为我在解析 HTML 时从 node 获取我的数组,因为我不断收到与 node.text! 不是 non-function type, 相关的错误,我无法解析它的索引。
  • componentsSeparatedByCharactersInSet 与使用 Swift 2 语法编写的公认答案相同

标签: swift macos cocoa swift4 multiline


【解决方案1】:

最简单的解决方案是通过分隔行来创建字符串数组

let string =
"""
Product 1 description
Product 1 color
Product 2 description
Product 2 color
"""

let list = string.components(separatedBy: CharacterSet.newlines)

然后就可以用

获取索引了
let indexOfProduct2Description = list.index(of: "Product 2 description")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多