WeeklyJump
WeeklyJump

Reputation: 23

How can Swift insert just 1 backslash \ in String?

Is it possible to replace white space " " with "\ " ? For example, I need to do make change as follows: "computer science" to "computer\ science".

This is to make my other command line executable with some directory that contains white space. It fails with white space, but doing:

myText = "computer science"
myTextRevised = myText.replacingOccurance(of: " ", with "\\ ")

but this just makes myText = "computer\\ science", which I don’t understand why two backslash appears.

It cannot leave just one backslash like, "computer\ science".

Is there any possible way to do this?

Upvotes: 1

Views: 2432

Answers (2)

Asfar Hussain Siddiqui
Asfar Hussain Siddiqui

Reputation: 562

Simply you can Add "\" backslash in ios swift language in such a way :

var str = "My string" + "\\"
print("\(string")

Upvotes: 0

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

myText = "computer science"
myTextRevised = myText.replacingOccurance(of: " ", with "\\ ")

Would actually store computer\science in myTextRevised. As expected first backslash is used to escape the second (that is to be displayed).

Oh! I guess you are seeing it in Playground. Playground would show you it like that. Didn't you observe that playground also shows \n to you for each print statement?

Upvotes: 2

Related Questions