简体   繁体   English

Swift - 从字符串中删除 " 字符

[英]Swift - Remove " character from string

I have a string which is "Optional("5")".我有一个字符串,它是“可选(“5”)”。 I need to remove the "" surrounding the 5. I have removed the 'Optional' by doing:我需要删除 5 周围的“”。我通过执行以下操作删除了“可选”:

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.我在删除 " 字符时遇到了困难,因为它们指定了代码中字符串的结尾。

Swift uses backslash to escape double quotes. Swift 使用反斜杠来转义双引号。 Here is the list of escaped special characters in Swift:以下是 Swift 中转义的特殊字符列表:

  • \\0 (null character) \\0 (空字符)
  • \\\\ (backslash) \\\\ (反斜杠)
  • \\t (horizontal tab) \\t (水平标签)
  • \\n (line feed) \\n (换行)
  • \\r (carriage return) \\r (回车)
  • \\" (double quote) \\" (双引号)
  • \\' (single quote) \\' (单引号)

This should work:这应该有效:

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

Swift 3 and Swift 4:斯威夫特 3 和斯威夫特 4:

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

Latest documents updated to Swift 3.0.1 have:更新到 Swift 3.0.1 的最新文档有:

  • Null Character ( \\0 )空字符 ( \\0 )
  • Backslash ( \\\\ )反斜杠 ( \\\\ )
  • Horizontal Tab ( \\t )水平制表符 ( \\t )
  • Line Feed ( \\n )换行符 ( \\n )
  • Carriage Return ( \\r )回车 ( \\r )
  • Double Quote ( \\" )双引号 ( \\" )
  • Single Quote ( \\' )单引号 ( \\' )
  • Unicode scalar ( \\u{n}\u003c/code> ), where n is between one and eight hexadecimal digits Unicode 标量 ( \\u{n}\u003c/code> ),其中 n 介于 1 到 8 个十六进制数字之间

If you need more details you can take a look to the official docs here如果您需要更多详细信息,可以在此处查看官方文档

Here is the swift 3 updated answer这是 swift 3 更新的答案

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})

To remove the optional you only should do this要删除可选项,您只需执行此操作

println("\(text2!)")

cause if you dont use "!"因为如果你不使用“!” it takes the optional value of text2它采用 text2 的可选值

And to remove "" from 5 you have to convert it to NSInteger or NSNumber easy peasy.并且要从 5 中删除 "",您必须将其转换为 NSInteger 或 NSNumber 容易的。 It has "" cause its an string.它有“”,因为它是一个字符串。

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

Replacing for Removing is not quite logical.替换为删除不是很合乎逻辑。 String.filter allows to iterate a string char by char and keep only true assertion. String.filter 允许逐个字符迭代字符串并只保留真正的断言。

Swift 4 & 5斯威夫特 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)

如果您想从字符串中删除更多字符,例如“a”、“A”、“b”、“B”、“c”、“C”,您可以这样做:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

As Martin R says, your string "Optional("5")" looks like you did something wrong.正如 Martin R 所说,你的字符串 "Optional("5")" 看起来你做错了什么。

dasblinkenlight answers you so it is fine, but for future readers, I will try to add alternative code as: dasblinkenlight 回答你所以很好,但对于未来的读者,我会尝试添加替代代码:

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.您的示例中的 text2 看起来像 String 并且它可能已经设置为 "" 但看起来您在某个地方有一个 Optional(String) 类型的 yourOriginalString ,它没有被正确转换或使用。

I hope this can help some reader.我希望这可以帮助一些读者。

Let's say you have a string:假设您有一个字符串:

var string = "potatoes + carrots"

And you want to replace the word "potatoes" in that string with "tomatoes"并且您想用“tomatoes”替换该字符串中的“potatoes”一词

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

If you print your string, it will now be: "tomatoes + carrots"如果你打印你的字符串,它现在将是: "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)空字符 (\\0)
  • Backslash (\\)反斜杠 (\\)
  • Horizontal Tab (\\t)水平制表符 (\\t)
  • Line Feed (\\n)换行符 (\\n)
  • Carriage Return (\\r)回车 (\\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"输出: "dog's toys + carrots"

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:如果您在尝试在可选的 Int 或 String 中打印 5 的值时获得输出 Optional(5),则应先解开该值:

if value != nil
{ print(value)
}

or you can use this:或者你可以使用这个:

if let value = text {
    print(value)
}

or in simple just 1 line answer:或者简单的只有 1 行答案:

print(value ?? "")

The last line will check if variable 'value' has any value assigned to it, if not it will print empty string最后一行将检查变量 'value' 是否有任何分配给它的值,如果没有,它将打印空字符串

You've instantiated text2 as an Optional (eg var text2: String?).您已将 text2 实例化为 Optional(例如 var text2: String?)。 This is why you receive Optional("5") in your string.这就是您在字符串中收到 Optional("5") 的原因。 take away the ?带走? and replace with:并替换为:

var text2: String = ""

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:如果尝试在可选的IntString 中打印5的值时获得输出Optional(5) ,则应先解开该值:

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.现在您已经获得了没有“可选”字符串的值,当该值之前没有解包时,Swift 添加了该字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM