99

I have a string which is "Optional("5")". I need to remove the "" surrounding the 5. I have removed the Optional by doing:

text2 = text2.stringByReplacingOccurrencesOfString("Optional(", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

I am having difficulties removing the " characters as they designate the end of a string in the code.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Calan Williams
  • 1,023
  • 1
  • 7
  • 6
  • 24
    If the string actually consists of the characters `Optional("5")` then probably something went wrong earlier, because that is the *description* of an optional string. It would make more sense to unwrap the optional before assigning to `text2`, instead of removing the "Optional(..)" textually. – Martin R Aug 31 '14 at 11:05

13 Answers13

189

Swift uses backslash to escape double quotes. Here is the list of escaped special characters in Swift:

  • \0 (null character)
  • \\ (backslash)
  • \t (horizontal tab)
  • \n (line feed)
  • \r (carriage return)
  • \" (double quote)
  • \' (single quote)

This should work:

text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
71

Swift 3 and Swift 4:

text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)

Latest documents updated to Swift 3.0.1 have:

  • Null Character (\0)
  • Backslash (\\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')
  • Unicode scalar (\u{n}), where n is between one and eight hexadecimal digits

If you need more details you can take a look to the official docs here

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
39

Here is the swift 3 updated answer

var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n})
pkamb
  • 33,281
  • 23
  • 160
  • 191
Mudith Chathuranga Silva
  • 7,253
  • 2
  • 50
  • 58
9

Replacing for Removing is not quite logical. String.filter allows to iterate a string char by char and keep only true assertion.

Swift 4 & 5

var aString = "Optional(\"5\")"

aString = aString.filter { $0 != "\"" }

> Optional(5)

Or to extend

var aString = "Optional(\"5\")"

let filteredChars = "\"\n\t"

aString = aString.filter { filteredChars.range(of: String($0)) == nil }

> Optional(5)
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29
  • Sorry Luc, your second example gives an error message. Argument type 'String.Element' (aka 'Character') does not conform to expected type 'StringProtocol'.. I guess you missed something? – user3069232 Dec 31 '19 at 17:12
8

To remove the optional you only should do this

println("\(text2!)")

cause if you dont use "!" it takes the optional value of text2

And to remove "" from 5 you have to convert it to NSInteger or NSNumber easy peasy. It has "" cause its an string.

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Norolim
  • 926
  • 2
  • 10
  • 25
8

I've eventually got this to work in the playground, having multiple characters I'm trying to remove from a string:

var otherstring = "lat\" : 40.7127837,\n"
var new = otherstring.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "la t, \n \" ':"))
count(new) //result = 10
println(new) 
//yielding what I'm after just the numeric portion 40.7127837
Getafix
  • 131
  • 2
  • 5
8

If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])
Grzegorz R. Kulesza
  • 1,324
  • 16
  • 10
4

As Martin R says, your string "Optional("5")" looks like you did something wrong.

dasblinkenlight answers you so it is fine, but for future readers, I will try to add alternative code as:

if let realString = yourOriginalString {
    text2 = realString
} else {
    text2 = ""
}

text2 in your example looks like String and it is maybe already set to "" but it looks like you have an yourOriginalString of type Optional(String) somewhere that it wasn't cast or use correctly.

I hope this can help some reader.

Taylor M
  • 1,855
  • 1
  • 14
  • 20
Dam
  • 579
  • 6
  • 22
  • 1
    That could be simplified a bit more with the nil-coalescing operator, e.g. `let resultingString = optionalString ?? ""`. – Kilian Jul 01 '16 at 20:46
2

Let's say you have a string:

var string = "potatoes + carrots"

And you want to replace the word "potatoes" in that string with "tomatoes"

string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)

If you print your string, it will now be: "tomatoes + carrots"

If you want to remove the word potatoes from the sting altogether, you can use:

string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)

If you want to use some other characters in your sting, use:

  • Null Character (\0)
  • Backslash (\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')

Example:

string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)

Output: "dog's toys + carrots"

  • This is the simplest and most effective way to do this. Instead changes the variable itself instead of making a new one. I tried hard to explain this in the best way possible so please remember to upvote this answer. – Mini Official Aug 30 '18 at 08:12
1

Swift 5 (working). Only 1 line code.

For removing single / multiple characters.

trimmingCharacters(in: CharacterSet)

In action:

var yourString:String = "(\"This Is: Your String\")"
yourString = yourString.trimmingCharacters(in: ["("," ",":","\"",")"])
print(yourString)

Output:

ThisIsYourString

You are entering a Set that contains characters you're required to trim.

Soorej Babu
  • 350
  • 2
  • 19
  • 2
    This is wrong answer. Trimming function removes characters only from start and end of string, leaves them inside string. – Anton Mar 11 '23 at 09:40
0

If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:

if value != nil
{ print(value)
}

or you can use this:

if let value = text {
    print(value)
}

or in simple just 1 line answer:

print(value ?? "")

The last line will check if variable 'value' has any value assigned to it, if not it will print empty string

Deepak Ghadi
  • 163
  • 2
  • 5
0

You can eighter escape characters with a \ or use # and here is how:


Swift 5

ou can use # symbol to specify a custom string delimiter.

When you use # with a string it affects the way Swift understands special characters in the string: \ no longer acts as an escape character, so \n literally means a “backslash“ than an “n” rather than a line break, and \(variable) will be included as those characters rather than using string interpolation.

So, these two strings are identical:

let regularString = "Optional(\"5\")"

let rawString = #"Optional("5")"#
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
-1

If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:

if let value = text {
    print(value)
}

Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.

Ale Mohamad
  • 372
  • 4
  • 7