2017-07-25 53 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)