首页 > 字符串替换的问题

字符串替换的问题

我的需求如下

var s = "helloxxxhelloxxxhelloxxx"

我已经根据正则匹配出多个hello来 存放在results数组里

for result in results {
   s.stringByReplacingOccurrencesOfString(result, withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
}

这时候我在遍历的时候希望 把原先字符串中含有hello的字符串给替换成“”, 我希望是每次遍历的时候只替换第一个hello,而不是全部的hello, 这种替换该怎么写呢?


加个?禁止贪婪匹配,不知道OC中怎么写


var s = "helloxxxhelloxxxhelloxxx"
while (s.rangeOfString("hello") != nil) {
    s = s.stringByReplacingCharactersInRange(s.rangeOfString("hello")!, withString: "")
}

rangeOfString会找到第一个匹配的字符串

【热门文章】
【热门文章】