2016-11-26 43 views
0

我想從字符串的未知長度中刪除一個單詞,這裏是我的代碼。從未知長度的字符串中移除一個單詞SWIFT

if (newService.range(of: serviceStr) != nil){ 

    // I should remove selected word here 

    print("remove selected") 
}else{ 
    print("add select") 
    let space = " , " 
    newService = newService + space + serviceStr    
} 

我已經嘗試了很多方法,但是,每一個代碼,我應該指定offsetBy這我不知道,因爲它的用戶按鈕選擇。

回答

7

你可以寫

import Foundation 

var sentence = "This is a simple sentence" 
let wordToRemove = "simple" 


if let range = sentence.range(of: wordToRemove) { 
    sentence.removeSubrange(range) 
} 

print(sentence) // This is a sentence 

如果您也想刪除簡單的單詞後面的額外空間替換此

let wordToRemove = "simple" 

與此

let wordToRemove = "simple " 
+0

真棒!有效! – OnlyPrograming

0

這如果你願意的話只需要刪除serviceStr

if let range = newService.range(of: serviceStr) { 
    print("remove selected") 
    newService.removeSubrange(range) 
} else { 
    print("add select") 
    newService += " , " + serviceStr    
} 

但是,如果您需要添加或刪除分隔,它更棘手,尤其是你的方式寫的:你首先總是串聯一個逗號,你不結束服務也是以字符串開頭的最初逗號開始的?

這裏有一個建議,得到乾淨的逗號支持:

let space = " , " 
if let range = newService.range(of: serviceStr) { 
    print("remove selected") 
    newService.removeSubrange(range) 
    newService = newService.components(separatedBy: space).filter({ !$0.isEmpty }).joined(separator: space) 
} else { 
    print("add select") 
    var components = newService.components(separatedBy: space) 
    components.append(serviceStr) 
    newService = components.joined(separator: space)   
} 
相關問題