Swift - remove single backslash

This is probably a stupid question, but I'm new to quick, and in fact I can't figure it out.

I have an API that returns url as the string " http: \ / \ / xxx ". I don't know how to save the URL returned by the API in this format. I cannot save it in a variable due to backslash.

From apple doc:

Line

... cannot contain uninsulated backslashes (\), ...

Is there a way to save a string like this and how to remove these single backslashes or how to work with it?

Thanks for every tip.

+4
source share
3 answers

, :

let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")

, , API, , . , -, , , .

, API , , , , , , .


, , . , " ". :

String . - , ("").

. - . String . String , "escape", ( ). :

:

  • \0 ( ), \\ ( ), \t ( ), \n (), \r ( ), \" ( ) \' ( )
  • Unicode, \u{n}, n - 1-8- , Unicode

, , , , . , , , \\.

, stringByReplacingOccurrencesOfString " string1, (.. )".

:

let string1 = "foo\\bar"

print(string1)                    // this will print "foo\bar"
print(string1.characters.count)   // this will print "7", not "8"

let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")

print(string2)                    // this will print "foobar"
print(string2.characters.count)   // this will print "6"

, string1 "" "" , (, "\\"). . \\ , . print , .

, (, stringByReplacingOccurrencesOfString) , .

+4

, .

+1

, .

let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let convertedStr = jsonStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
print(convertedStr)
0
source

Source: https://habr.com/ru/post/1618192/


All Articles