Joe Huang
Joe Huang

Reputation: 6570

In Swift, how to remove hashtags in a string?

For example, a string = I am a #hashtag1 string #hashtag2 Hi!

In Swift 2, what's the ideal way to remove the hashtags so the string becomes I am a string Hi!

Hashtags are not fixed strings. It can be any string that starts with #. This question shouldn't be marked as duplicate as this question.

Upvotes: 1

Views: 895

Answers (4)

krishna
krishna

Reputation: 69

You can use the below statements:

let aString = "I am a #hashtag1 string .#hashtag2 Hi!"

let newString = aString.replacingOccurrences(of: "#hashtag", with: "")

Upvotes: 0

Dániel Nagy
Dániel Nagy

Reputation: 12045

Or using reduce, but loosing readability:

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

Upvotes: 1

vadian
vadian

Reputation: 285240

A solution with regular expression

let string = "I am a #hashtag1 string #hashtag2 Hi!"
let withoutHashTags = string.stringByReplacingOccurrencesOfString("#(?:\\S+)\\s?", 
                             withString: "", 
                                options: .RegularExpressionSearch, 
                                  range: Range(string.startIndex..<string.endIndex))

To remove hashtags without a leading space this slightly altered version can be used. However there is one remaining assumption: The hashtag must be separated from the successive word by a space or is the end of the string.

let withoutHashTags = string.stringByReplacingOccurrencesOfString("\\s?#(?:\\S+)\\s?",
                      withString: " ",
                      options: .RegularExpressionSearch,
                      range: Range(string.startIndex..<string.endIndex))
                      .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

Upvotes: 7

Eendje
Eendje

Reputation: 8883

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!

Edit:

Back with a oneliner :p, still a bit too complicated for my taste though.

Upvotes: 1

Related Questions