例如,字符串= I am a #hashtag1 string #hashtag2 Hi!
在Swift 2中,删除主题标签的理想方法是使字符串变为I am a string Hi!
Hashtags不是固定字符串。它可以是以#
开头的任何字符串。此问题不应标记为this question重复。
答案 0 :(得分:7)
具有正则表达式的解决方案
let string = "I am a #hashtag1 string #hashtag2 Hi!"
let withoutHashTags = string.stringByReplacingOccurrencesOfString("#(?:\\S+)\\s?",
withString: "",
options: .RegularExpressionSearch,
range: Range(string.startIndex..<string.endIndex))
要删除没有前导空格的主题标签,可以使用此略微更改的版本。但是还有一个假设:主题标签必须用空格与连续的单词分隔,或者是字符串的结尾。
let withoutHashTags = string.stringByReplacingOccurrencesOfString("\\s?#(?:\\S+)\\s?",
withString: " ",
options: .RegularExpressionSearch,
range: Range(string.startIndex..<string.endIndex))
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
答案 1 :(得分:1)
或使用reduce
,但失去了可读性:
let testString = "I am a #hashtag1 string .#hashtag2 Hi!"
let reducedValue = testString.characters.reduce(("", true)) {
if $0.1 && $1 != "#" {
return ("\($0.0)\($1)", true)
} else if $0.1 && $1 == "#" {
return ("\($0.0)", false)
} else if let last = $0.0.characters.last where !$0.1 && $1 == " " && last == " " {
return ("\($0.0)", true)
} else if !$0.1 && $1 == " " {
return ("\($0.0)\($1)", true)
} else {
return ("\($0.0)", false)
}
let result = reducedValue.0
答案 2 :(得分:1)
Oneliner:
let text = "I am a #hashtag1 string #hashtag2 Hi!"
let test = text.componentsSeparatedByString(" ").filter { !$0.containsString("#hashtag") }.joinWithSeparator(" ")
print(test) // I am a string Hi!
编辑:
回到oneliner:p,虽然我的口味仍然有点过于复杂。
答案 3 :(得分:0)
您可以使用以下声明:
让aString =&#34;我是#hashtag1字符串。#hashtag2嗨!&#34;
让newString = aString.replacingOccurrences(of:&#34; #hashtag&#34;,with:&#34;&#34;)