How to Remove Quotes from String on Swift

How can I remove quotes from String on Swift?

You can simply use

Swift 1

var str: String = "\"Hello\""

print(str) // "Hello"

print(str.stringByReplacingOccurrencesOfString("\"", withString: "")) // Hello

Update for Swift 3 & 4

print(str.replacingOccurrences(of: "\"", with: "")) // Hello

How can I remove quotes from String on Swift?

You can simply use

Swift 1

var str: String = "\"Hello\""

print(str) // "Hello"

print(str.stringByReplacingOccurrencesOfString("\"", withString: "")) // Hello

Update for Swift 3 & 4

print(str.replacingOccurrences(of: "\"", with: "")) // Hello

Remove surrounding quotes from a Swift String while keeping Inner Quotes similar to Kotlin command string.removeSurrounding

You can create your own string removeSurrounding method extending StringProtocol, you just need to check if the original string starts and ends with a specific character and return the original dropping the first and last characters otherwise return it unchanged:

extension StringProtocol {
/// Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.
func removingSurrounding(_ character: Character) -> SubSequence {
guard count > 1, first == character, last == character else {
return self[...]
}
return dropFirst().dropLast()
}
}

And to create a mutating version of the same method you just need to constrain the extension to RangeReplaceableCollectionn declare your method as mutating and use the mutating methods removeFirst and removeLast instead of dropFirst and dropLast:

extension StringProtocol where Self: RangeReplaceableCollection {
mutating func removeSurrounding(_ character: Character) {
guard count > 1, first == character, last == character else {
return
}
removeFirst()
removeLast()
}
}

Playground testing:

let string1 = #""-5 -5"" -Animated -Cartoon""#
let string2 = #""-POTF -Force -12 -12"""#
let newstring1 = string1.removingSurrounding("\"").replacingOccurrences(of: "\"\"", with: "\"") // "-5 -5" -Animated -Cartoon"
let newstring2 = string2.removingSurrounding("\"").replacingOccurrences(of: "\"\"", with: "\"") // "-POTF -Force -12 -12""

SwiftUI getting rid of quotes in a string variable

Since the double quotes offered by Xcode and Device Keyboard are different, you can try this way to ensure that different types of double quotes from these different devices will be removed effectively.

import SwiftUI

struct Practice: View {
@State private var test = ""
@State private var test2 = "\"Hello\""
var body: some View {
TextField("enter", text: $test)
Button {
test = test
.replacing("\u{022}", with: "")
.replacing("\u{201c}", with: "")
.replacing("\u{201d}", with: "")
test2 = test2
.replacing("\u{022}", with: "")
.replacing("\u{201c}", with: "")
.replacing("\u{201d}", with: "")
print(test)
print(test2)
} label: {
Text("remove")
}

}
}

Trim double quotation mark( ) from a string

trimmingCharacters(in is the wrong API. It removes characters from the beginning ({") and end (}) of a string but not from within.

What you can do is using replacingOccurrences(of with Regular Expression option.

let trimmedStr = str.replacingOccurrences(of: "[\"{\\]}]", with: "", options: .regularExpression)

[] is the regex equivalent of CharacterSet.

The backslashes are necessary to escape the double quote and treat the closing bracket as literal.


But don't trim. This is a JSON string. Deserialize it to a dictionary

let str = """
{"fileId":1902,"x":38,"y":97}
"""

do {
let dictionary = try JSONSerialization.jsonObject(with: Data(str.utf8)) as! [String:Int]
print(dictionary)
} catch {
print(error)
}

Or even to a struct

struct File : Decodable {
let fileId, x, y : Int
}

do {
let result = try JSONDecoder().decode(File.self, from: Data(str.utf8))
print(result)
} catch {
print(error)
}

How to remove double quotes and brackets from NSString

Use following code:

NSCharacterSet *unwantedChars = [NSCharacterSet characterSetWithCharactersInString:@"\"[]"];
NSString *requiredString = [[_finalIDStr componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString: @""];

It's efficient and effective way to remove as many characters from your string in one single line..

Convert string into array without quotation marks in Swift 3

You can apply a flatMap call on the [String] array resulting from the call to components(separatedBy:), applying the failable init(_:radix:) of Int in the body of the transform closure of the flatMap invokation:

let strNumbers = "1 2 3 4"
let numbersArray = strNumbers
.components(separatedBy: " ")
.flatMap { Int($0) }

print(numbersArray) // [1, 2, 3, 4]
print(type(of: numbersArray)) // Array<Int>


Related Topics



Leave a reply



Submit