如何用swift 3中的链接(http)替换子字符串?

时间:2017-07-25 17:06:24

标签: swift replace swift3 substring

我有一个字符串和子字符串(http),我想替换那个子字符串,但我不知道该子字符串何时结束。我的意思是想要检查它,直到一个空间没有来,之后我想要更换它。 我正在检查如果我的字符串包含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"

2 个答案:

答案 0 :(得分:6)

可能的解决方案是正则表达式

模式搜索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)

答案 1 :(得分: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)