如何在Swift中获取多行字符串文字的索引

问题描述 投票:0回答:1

我正在尝试查找与指定值匹配的字符串的索引。一种方法是使用实​​例方法,但这假设我正在使用数组;我正在使用多行字符串文字。关于此主题的大部分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计算器找到并定义匹配来完成我程序中的第一个变量,但是我在完成第二个变量时遇到了麻烦。我已经尝试拆分列表并制作元组,但是当我在列表中加入0时,每个字符串都产生了enumerated()的索引。也就是说,如果有人可以帮助我以下任何一个,我将非常感谢帮助:

  • 获取上述多行字符串文字的索引值
  • 定义一个count变量,其值是一个在每个字符串迭代中更改的整数
  • 将上面的多行字符串文字转换为一个列表,每个字符串都有一个索引
swift macos cocoa swift4 multiline
1个回答
3
投票

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

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")
© www.soinside.com 2019 - 2024. All rights reserved.