Randall Stephens
Randall Stephens

Reputation: 1057

How do I remove "\U0000fffc" from a string in Swift?

I have added an image to a textfield, and wish to remove it again. I've tried the following two lines to no avail?

string = string.stringByReplacingOccurrencesOfString("\\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
string = string.stringByReplacingOccurrencesOfString("\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

Any help would be greatly appreciated, thanks so much!

Upvotes: 3

Views: 3161

Answers (2)

Martin R
Martin R

Reputation: 539965

Unicode escape sequences are differently in Swift from those in Objective-C, the Unicode character U+FFFC is escaped as \u{fffc}:

This is your string:

var string = "Hello\n\n\u{fffc}"
println(string.dataUsingEncoding(NSUTF32BigEndianStringEncoding)!)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a 0000fffc>

Now remove all U+FFFC characters:

string = string.stringByReplacingOccurrencesOfString("\u{fffc}", withString: "")
println(string.dataUsingEncoding(NSUTF32BigEndianStringEncoding)!)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a>

Note that options: and range: are optional parameters and not needed in this case.


Update for Swift 3/4:

var string = "Hello\n\n\u{fffc}"
print(string.data(using: .utf32BigEndian)! as NSData)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a 0000fffc>

string = string.replacingOccurrences(of: "\u{fffc}", with: "")
print(string.data(using: .utf32BigEndian)! as NSData)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a>

Upvotes: 13

Eric Aya
Eric Aya

Reputation: 70113

The method stringByReplacingOccurrencesOfString can work on parts of the string or the whole string.

For example, this works on the entire string, by giving it the range from start of the string to the end:

let original = "First part \\U0000fffc Last part"

let originalRange = Range<String.Index>(start: original.startIndex, end: original.endIndex)

let target = original.stringByReplacingOccurrencesOfString("\\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: originalRange)

println(target) // prints "First part  Last part"

Upvotes: 2

Related Questions