gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:11:18 24 4
gpt4 key购买 nike

我正在尝试查找与指定值匹配的字符串的索引。一种方法是使用实​​例方法,但这假设我正在使用数组;我正在使用多行字符串文字。大部分 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 的索引。也就是说,如果有人可以帮助我解决以下任何问题,我将不胜感激:

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

最佳答案

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

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")

关于swift - 如何在 Swift 中获取多行字符串文字的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com