16

I want to replace some text in a string with another string.

For example : A string equals to "Red small car". I want to replace "small" with "big" so the string becomes "Red big car". I have to do this in swift. Thanks.

thura oo
  • 493
  • 1
  • 6
  • 18

2 Answers2

35

You can try using stringByReplacingOccurrencesOfString

let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")

Edit In Swift 5

import Foundation

let string = "Big red car"
let replaced = string.replacingOccurrences(of: "Big", with: "Small")
rakeshbs
  • 24,392
  • 7
  • 73
  • 63
  • This gives me an error in REPL: `error: cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(StringLiteralConvertible, withString: StringLiteralConvertible)'`, w.o. the cast, it works. – Sebastian Jan 15 '15 at 12:17
  • 2
    @SebastianDressler: Which Xcode version are you using? That code compiles and works fine (as well as yours) in Xcode 6.1.1. Of course, using NSString in the REPL requires that you `import Foundation`. – Anyway, this question has already been asked and answered (probably more than once). – Martin R Jan 15 '15 at 12:22
  • @MartinR it is 6.1.1 and I imported `Foundation`. Very strange... – Sebastian Jan 15 '15 at 12:23
  • @SebastianDressler: Indeed. – Martin R Jan 15 '15 at 12:46
  • 3
    For Swift 3, you will want to use `let replaced = string.replacingOccurrences(of:"Big" with "Small")` – Alex Shaffer Apr 12 '17 at 18:04
  • 1
    @AlexShaffer the comma should be added before "with", also colon be added after "with": `let replaced = string.replacingOccurrences(of:"Big", with:"Small")` – Richter Dec 05 '19 at 06:36
15

You can use stringByReplacingOccurrencesOfString, e.g.

let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")
Sebastian
  • 8,046
  • 2
  • 34
  • 58