usinuniverse
usinuniverse

Reputation: 760

How to remove specific characters or words from a string in swift?

var myString = "43321 This is example hahaha 4356-13"

And I want result that

var resultString = "This is example"

In other words, I want to erase certain words and numbers.

How is it possible?

I've already done a search, But I could not find exactly what I wanted.

Please answer me. Thanks


Okay, To be precise, I want to erase all numbers and erase only certain words I want.


I made a big mistake. I am so sorry. To be precise, it is correct to erase numbers and certain words. However, I should not always delete all digits, but keep them if number's are next to a string.

example)

let testString1 = "123123123123"
let testString2 = "apple 65456876"
let testString3 = "apple banana3 horse5"
let testString4 = "44 apple banana1banana 5horse"
let testString5 = "123 banana123 999"

And I want remove words "apple".

So result is

let resultString1 = ""
let resultString2 = ""
let resultString3 = "banana3 horse5"
let resultString4 = "banana1banana 5horse"
let resultString5 = "banana123"

Upvotes: 3

Views: 5608

Answers (5)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Use this string extension .

extension String

{
 func removeNumbersAString(str:String)->String
 {

    var aa = self.components(separatedBy: CharacterSet.decimalDigits).joined(separator: " ")

    let regexp = " \\d* "
    var present = self
    while present.range(of:regexp, options: .regularExpression) != nil  {
        if let range = present.range(of:regexp, options: .regularExpression) {
            let result = present.substring(with:range)

           present = present.replacingOccurrences(of: result, with: "")

           // print("before \(result)")
        }
    }

    return present
 }

}

A test

 var str = "dsghdsghdghdhgsdghghdghds 12233 apple"

 print("before \(str)")   /// before dsghdsghdghdhgsdghghdghds 12233 apple

 print("after \(str.removeNumbersAString(str: "apple"))")    /// after dsghdsghdghdhgsdghghdghds

Upvotes: 1

Ben Ong
Ben Ong

Reputation: 931

I think this will be faster with a regex solution:

//use NSMutableString so the regex.replaceMatches later will work
var myString:NSMutableString = "43321 This is example hahaha 4356-13"

//add more words to match by using | operator e.g. "[0-9]{1,}|apple|orange"
//[0-9]{1,} simply removes all numbers but is more efficient than [0-9]
let regexPattern = "[0-9]{1,}|apple"

//caseInsensitive or the regex will be much longer
let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive) 

var matches = regex.matches(in: myString as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: myString, options: .withoutAnchoringBounds, range: range, withTemplate: "")

print(myString) // This is example hahaha -

Subsequent Strings

var testString3: NSMutableString = "apple banana horse"
matches = regex.matches(in: testString3 as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: testString3, options: .withoutAnchoringBounds, range: range, withTemplate: "")
print(testString3) // banana horse

Upvotes: 1

iGatiTech
iGatiTech

Reputation: 2268

You can try applying below code,

var sentence = "43321 This is example hahaha 4356-13"
sentence = (sentence.components(separatedBy: NSCharacterSet.decimalDigits) as NSArray).componentsJoined(by: "")
let wordToRemove = "hahaha"


if let range = sentence.range(of: wordToRemove) {
   sentence.removeSubrange(range)
}

print(sentence) // This is example -

Upvotes: 2

Priya
Priya

Reputation: 749

Try bellow code:

var myString = "43321 This is example hahaha 4356-13"
        //to remove numbers
        myString = (myString.components(separatedBy: NSCharacterSet.decimalDigits) as NSArray).componentsJoined(by: "")

        // to remove specific word
        if let range = myString.range(of: "hahaha") {
            myString.removeSubrange(range)
        }
        print(myString)

Upvotes: 0

Madhur
Madhur

Reputation: 1116

You can try this :

   let myString = "43321 This is example hahaha 4356-13"
              let stringToReplace = "43321"
              let outputStr = myString.replacingOccurrences(of: stringToReplace, with: "")
             print(outputStr.trimmingCharacters(in: NSCharacterSet.whitespaces))

//output: This is example hahaha 4356-13

Upvotes: 1

Related Questions