2017-07-25 55 views
1

我有一個字符串和子字符串(http),我想要替換該子字符串,但我不知道該子字符串何時結束。我的意思是要檢查它,直到一個空間不來,然後我想替換它。 我正在檢查,如果我的字符串包含http也是一個字符串,那麼我想在空間到來時將其替換。這裏下面如何用swift 3中的鏈接(http)替換子字符串?

是我的例子: -

let string = "Hello.World everything is good http://www.google.com By the way its good". 

這是我的字符串,可以是動態的也是我的意思是在這上面的字符串HTTP是存在的,所以我想,以取代「http://www.google.com」到「網站」。 因此,這將是

string = "Hello.World everything is good website By the way its good" 

回答

4

一個可能的解決方案是正則表達式

模式搜索http://https://跟着一個或多個非空白字符,直到達到一個字邊界。

let string = "Hello.World everything is good http://www.google.com By the way its good" 
let trimmedString = string.replacingOccurrences(of: "https?://\\S+\\b", with: "website", options: .regularExpression) 
print(trimmedString) 
+0

我剛剛發佈了這個帖子,但是使用'「https?:// [^] *」'的正則表達式。這允許http和https。 – rmaddy

+0

感謝您的改進。我加了'?' – vadian

+0

好的,謝謝。還有一件事是在https之前我想添加「Website」並且我想保留「http」的東西? – kishor0011

1

拆分每個單詞,替換並回去應該解決這個問題。

// split into array 
let arr = string.components(separatedBy: " ") 

// do checking and join 
let newStr = arr.map { word in 
    return word.hasPrefix("http") ? "website" : word 
}.joined(separator: " ") 

print(newStr)