请教一个 Swift 问题:
假设 strRawData 是某个文本档案的全部内容,用 pseudo code 说明一下:
arrRawData = strRawData.components(separatedBy: " ") // 用一个 ASCII 空格分开
for neta in arrRawData { 请问在这里该怎样获取 neta 相对于 strRawData 的 startIndex 和 endIndex ? (两者的类别都是 String.Index 或任何更适合的类型。) }
问这个问题的原因是我想在 Swift 内找到可以模拟 std::string_view
的方法。
1
chipmuck 2022-05-07 14:22:51 +08:00
```swift
let abc = "aaaa bbbb cccc dddd eeee ffff" let comps = abc.components(separatedBy: " ") for element in comps { let startIndex = abc.range(of: element)?.lowerBound let endIndex = abc.range(of: element)?.upperBound // ... } ``` 像这样? |
3
MrKrabs 2022-05-07 20:24:18 +08:00
let array = ["a", "b", "", "c"]
let str = array.joined(separator: " ") let splited = str.split(separator: " ", omittingEmptySubsequences: false) splited.forEach { sub in print(str.distance(from: str.startIndex, to: sub.startIndex), str[sub.startIndex..<sub.endIndex]) } 要省空间用 lazy split https://github.com/apple/swift-algorithms/blob/main/Guides/Split.md |
4
shoujiaxin 2022-05-07 21:02:30 +08:00
用 split 试试?返回的是 Substring 的数组,Substring 和原 String 共享文本存储,Substring 的 startIndex 应该就是原 String 的索引
|
5
ShikiSuen OP @shoujiaxin @MrKrabs
谢谢二位。不知道这样处理是否可以正常处理包含 Emoji 的内容。 ``` let strData = #""" # Comment: These are test data treeNewBee 🌳🐮🍺 -0.1145141919810 cowbeer 🐂🍺 -2.390804 """# ``` |
6
shoujiaxin 2022-05-08 13:14:44 +08:00
@ShikiSuen Swift 的字符串是尽可能保证 Unicode 正确的
|
7
ShikiSuen OP @shoujiaxin 太感謝了。
|