2016-09-09 26 views
-3

Stringから部分文字列の先頭と末尾に文字を追加する必要があるプロジェクトに取り組んでいます。 例iOSのStringからSubStringの先頭と末尾に文字を追加Swift

Given String 
"Hello http://google.com Google." 
Result should be 
"Hello <a href="">http://www.google.com</a> The site for google." 

それが動的であるように私はサブの場所について確認していないのでご注意ください。 アドバイスをお願いします。

+2

正規表現を置き換えますか? – dasblinkenlight

+0

正規表現にするべきことをアドバイスしてください。 –

答えて

2

NSDataDetectorを使用すると、文字列 に埋め込まれているリンクを見つけて、それらを置き換えることができます。例(インライン説明):

var string = "Hello http://google.com Google, hello http://www.apple.com Apple." 
var nsString = string as NSString // NSString needed in order to work with NSRange 

// Data detector for embedded links: 
let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue) 
let matches = detector.matchesInString(string, options: [], 
             range: NSRange(location: 0, length: nsString.length)) 

// Replace links, starting with the last one, otherwise ranges would change: 
for match in matches.reverse() { 
    if let url = match.URL { 
     let replacement = "<href=\"\(url.absoluteString)\"></a>" 
     nsString = nsString.stringByReplacingCharactersInRange(match.range, withString: replacement) 
    } 
} 
string = nsString as String 
print(string) 
// Hello <href="http://google.com"></a> Google, hello <href="http://www.apple.com"></a> Apple. 
関連する問題