2016-04-01 74 views

回答

5

替代非正則表達式的解決方案:

let foo = "This  is  a string with a lot of spaces!" 
let bar = foo 
    .componentsSeparatedByString(" ") 
    .filter { !$0.isEmpty } 
    .joinWithSeparator("_") 

print(bar) /* This_is_a_string_with_a_lot_of_spaces! */ 

作品也爲Unicode字符(感謝@MartinR這個美麗的例子)

let foo = "  " 

// ... 

/* _____ */ 
+1

這是一個非常漂亮的過濾器使用。 –

+1

@NateBirkholz然而,我應該指出,上面的這個方法不會分別替換第一個和最後一個單詞之前和之後的空格組;這些空格將被刪除(例如''這是一個帶有大量空格的字符串!「'將產生與'」這是一個有很多空格的字符串!「')。 – dfri

+0

這正是我所需要的,所以這不會是一個問題 – sloeberGJ

3

您可以使用一個簡單的正則表達式替換做到這一點:

let myString = "  " 
if let regex = try? NSRegularExpression(pattern: "\\s+", options: []) { 
    let replacement = regex.stringByReplacingMatchesInString(myString, options: .WithTransparentBounds, range: NSMakeRange(0, (myString as NSString).length), withTemplate: "_") 
    print(replacement) 
    // "_____" 
} 
+1

用'let myString =「」'測試你的代碼...... :) –

+3

WHHHYYYYY UNICODE WHYYYY – brandonscript

4

@remus建議可以簡化(並製作Unicode/Emoji/Fla克安全的)作爲

let myString = " This  is  a string with a lot of spaces!   " 
let replacement = myString.stringByReplacingOccurrencesOfString("\\s+", withString: "_", options: .RegularExpressionSearch) 
print(replacement) 
// _This_is_a_string_with_a_lot_of_spaces!____ 
1

替代非正則表達式,純夫特(無橋接至NSString)溶液:

let spaced = "This  is  a string with a lot of spaces!" 

let under = spaced.characters.split(" ", allowEmptySlices: false).map(String.init).joinWithSeparator("_") 

替代,替代版本不刪除前導和轉換時尾隨空格。稍有模糊爲了簡潔... ;-)

let reduced = String(spaced.characters.reduce([Character]()) { let n = $1 == " " ? "_" : $1; var o = $0; o.append(n); guard let e = $0.last else { return o }; return e == "_" && n == "_" ? $0 : o }) 

有可能涉及flatMap()一個更聰明的解決方案,但我會留給別人比我更聰明!

+0

只需注意,就像在@dfris的解決方案中一樣,這將刪除並不替換初始和尾隨空格。 –

+0

@MartinR注意和更新! – ColGraff

相關問題