2016-11-10 23 views
1

我有一組串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) 
+0

我不完全清楚你想要做什麼。你可以發佈你的使用'for'循環的代碼嗎? – ganzogo

+0

@ganzogo是的,明天早上我會發布它(在意大利已經晚了),因爲我想先做一些修改。 – Nisba

+0

@ganzogo編程時很難睡覺,我正在編輯我的問題併發布我的臨時解決方案 – Nisba

回答

1

我不知道如果我有一些事情翻轉左右,但根據聯合國的我的你的問題這個的理解是,我會做什麼:

func findFirstContaining(needle item: String, in haystack: [String]) -> String? { 

    let stringRanges: [Range<String.Index>] = haystack.flatMap { return item.range(of: $0) } .sorted { $0.lowerBound < $1.lowerBound } 
    if let range = stringRanges.first { 
     return item.substring(with: range) 
    } 
    else { 
     return nil 
    } 
} 

let testSet: Set<String> = ["test", "string", "set"] 

let needle = "this is a test" 

// evaluates to "test" 
let result = findFirstContaining(needle: needle, in: testSet.sorted()) 

let reversedResult = findFirstContaining(needle: needle, in: testSet.sorted().reversed()) 

這可能是低效的,但我米不完全確定你想要解決什麼問題。

+0

謝謝,明天我會閱讀它,現在我發佈我的解決方案。 – Nisba

相關問題