我有一組串set
的,我想找到一個set
字符串中第一次出現的字符串string
的字符串。 我想從position
(整數)向後搜索。字符串向後查找屬於一組第一串(正則表達式?)
我寫了一個使用for循環的代碼,但我希望能夠以更緊湊的方式編寫它,也許正則表達式是必需的。
你能幫我嗎?
編輯。我的臨時解決方案:currentPosition
是一個整數值,由NSTextView
給出,command
是我操縱的字符串,我現在正在做的是檢查currentPosition
之後的字符是否爲" "
或者它是否爲最後一個字符串command
。在這種情況下,我推斷command
的子字符串從currentPosition
到最接近的(在反向)分隔符(在我的代碼中定義)。
什麼在我的問題是所謂的set
這裏是一個String數組,它是由separators
表示,究竟是什麼string
這裏是command
,什麼是position
這裏是currentPosition
。
let currentPosition = self.selectedRange().location
let currentPositionIndex = command.index(command.startIndex,offsetBy: currentPosition)
if(currentPosition == command.characters.count || command[currentPositionIndex] == " ") {
let separatorsString = " .,:~/!+=\\;/?"
let separators = separatorsString.characters
//TODO: use regex in order to clean the code
var nearestSeparatorPosition = command.startIndex
outerloop: for i in stride(from: currentPosition - 1, to: -1, by: -1) {
for separator in separators {
let index = command.index(command.startIndex, offsetBy: i)
if(command[index] == separator) {
nearestSeparatorPosition = command.index(index, offsetBy: 1)
break outerloop
}
}
}
Swift.print("current word index = (\(command.distance(from: command.startIndex, to: nearestSeparatorPosition)),\(command.distance(from: command.startIndex, to: currentPositionIndex)))")
let currentWord = command.substring(with: nearestSeparatorPosition ..< currentPositionIndex)
我不完全清楚你想要做什麼。你可以發佈你的使用'for'循環的代碼嗎? – ganzogo
@ganzogo是的,明天早上我會發布它(在意大利已經晚了),因爲我想先做一些修改。 – Nisba
@ganzogo編程時很難睡覺,我正在編輯我的問題併發布我的臨時解決方案 – Nisba