Swift:获取String中单词的开头和结尾字符的索引

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

字符串:

"[email protected], [email protected], [email protected], [email protected]"

通过手势识别器,我能够获得用户点击的角色(很高兴提供代码,但此时没有看到相关性)。

让我们说用户在o上点击"[email protected]"而字符index39

鉴于39 indexo,我想获得c开始的"[email protected]"的字符串起始索引,以及来自index m结束的"com"的结束"[email protected]"

换句话说,如果在index中使用characterString,我需要在indexleft上获得right,然后我们在左边的String和右边的comma遇到一个空间。

尝试过,但这只提供字符串中的最后一个字:

if let range = text.range(of: " ", options: .backwards) {
  let suffix = String(text.suffix(from: range.upperBound)) 
  print(suffix) // [email protected]
}

我不知道从哪里开始?

ios swift xcode nsstring
3个回答
3
投票

您可以在给定字符串的两个切片上调用range(of:)text[..<index]是给定字符位置之前的文本,text[index...]是从给定位置开始的文本。

例:

let text = "[email protected], [email protected], [email protected], [email protected]"
let index = text.index(text.startIndex, offsetBy: 39)

// Search the space before the given position:
let start = text[..<index].range(of: " ", options: .backwards)?.upperBound ?? text.startIndex

// Search the comma after the given position: 
let end = text[index...].range(of: ",")?.lowerBound ?? text.endIndex

print(text[start..<end]) // [email protected]

如果没有找到空格(或逗号),range(of:)调用都会返回nil。在这种情况下,nil-coalescing运算符??用于获取开始(或结束)索引。

(请注意,这是有效的,因为Substrings与其原始字符串共享一个公共索引。)


另一种方法是使用“数据检测器”,以便URL检测不依赖于某些分隔符。

示例(比较How to detect a URL in a String using NSDataDetector):

let text = "[email protected], [email protected], [email protected], [email protected]"
let index = text.index(text.startIndex, offsetBy: 39)

let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: text, range: NSRange(location: 0, length: text.utf16.count))

for match in matches {
    if let range = Range(match.range, in: text), range.contains(index) {
        print(text[range])
    }
}

2
投票

不同的方法:

你有字符串和Int索引

let string = "[email protected], [email protected], [email protected], [email protected]"
let characterIndex = 39

String.Index获取Int

let stringIndex = string.index(string.startIndex, offsetBy: characterIndex)

将字符串转换为地址数组

let addresses = string.components(separatedBy: ", ")

将地址映射到字符串中的范围(Range<String.Index>

let ranges = addresses.map{string.range(of: $0)!}

获取包含Int的范围的(stringIndex)索引

if let index = ranges.index(where: {$0.contains(stringIndex)}) {

获取相应的地址

let address = addresses[index] }

0
投票

一种方法可能是将原始字符串拆分为“,”然后使用简单的数学运算来查找给定位置(39)存在于数组的哪个元素,并从那里获得前一个空格和下一个逗号的正确字符串或索引取决于您的最终目标。

© www.soinside.com 2019 - 2024. All rights reserved.