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.

1
  • 1
    He's a newbie, please don't dislike him. It will make him disappointed about StackOverflow. Commented Jan 16, 2015 at 9:58

2 Answers 2

36

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")
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@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).
@MartinR it is 6.1.1 and I imported Foundation. Very strange...
For Swift 3, you will want to use let replaced = string.replacingOccurrences(of:"Big" with "Small")
@AlexShaffer the comma should be added before "with", also colon be added after "with": let replaced = string.replacingOccurrences(of:"Big", with:"Small")
|
15

You can use stringByReplacingOccurrencesOfString, e.g.

let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")

1 Comment

replacingOccurrences(of:,with:) in swift 4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.