(Swift) How to Print "\" Character in a String

(Swift) how to print \ character in a string?

For that and also future reference:

\0 – Null character (that is a zero after the slash)
\\ – Backslash itself. Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t – Horizontal tab
\n – Line Feed
\r – Carriage Return
\” – Double quote. Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’ – Single Quote. Similar reason to above.

Any way to replace characters on Swift String?

This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.

You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.

let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")

Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

let aString = "Some search text"

let replaced = String(aString.map {
$0 == " " ? "+" : $0
})

Swift - Remove character from string

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)

Printing a string with newline as text ( example \n example in one line)

you can split the string by newline and join it with any visible character you like (in the example with ~~~)

myString.components(separatedBy: CharacterSet.newlines).joined(separator: "~~~")

Get nth character of a string in Swift programming language

Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5.

Swift 4 or later

The Substring type was introduced in Swift 4 to make substrings
faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return.

Try it out here

extension StringProtocol {
subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
subscript(range: Range) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex.. }
subscript(range: ClosedRange) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex.. }
subscript(range: PartialRangeFrom) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
subscript(range: PartialRangeThrough) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
subscript(range: PartialRangeUpTo) -> SubSequence { self[..}

To convert the Substring into a String, you can simply
do String(string[0..2]), but you should only do that if
you plan to keep the substring around. Otherwise, it's more
efficient to keep it a Substring.

It would be great if someone could figure out a good way to merge
these two extensions into one. I tried extending StringProtocol
without success, because the index method does not exist there.
Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementation


Why is this not built-in?

The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift:

Subscripting strings with integers is not available.

The concept of "the ith character in a string" has
different interpretations in different libraries and system
components. The correct interpretation should be selected
according to the use case and the APIs involved, so String
cannot be subscripted with an integer.

Swift provides several different ways to access the character
data stored inside strings.

  • String.utf8 is a collection of UTF-8 code units in the
    string. Use this API when converting the string to UTF-8.
    Most POSIX APIs process strings in terms of UTF-8 code units.

  • String.utf16 is a collection of UTF-16 code units in
    string. Most Cocoa and Cocoa touch APIs process strings in
    terms of UTF-16 code units. For example, instances of
    NSRange used with NSAttributedString and
    NSRegularExpression store substring offsets and lengths in
    terms of UTF-16 code units.

  • String.unicodeScalars is a collection of Unicode scalars.
    Use this API when you are performing low-level manipulation
    of character data.

  • String.characters is a collection of extended grapheme
    clusters, which are an approximation of user-perceived
    characters.


Note that when processing strings that contain human-readable text,
character-by-character processing should be avoided to the largest extent
possible. Use high-level locale-sensitive Unicode algorithms instead, for example,
String.localizedStandardCompare(),
String.localizedLowercaseString,
String.localizedStandardRangeOfString() etc.

How to print an array of characters in swift without a line terminator

In a Playground you need to print one final newline, otherwise the output
is not flushed to the output window:

for chrInStr in strTokenizeMe { print(chrInStr, terminator: " ")}
print()

A (not necessarily better) alternative would be to concatenate
the characters before printing them:

print(strTokenizeMe.map(String.init).joined(separator: " "))

The problem does not occur when running a compiled program, because
the standard output is always flushed on program exit.

Swift - remove single backslash

You can just replace those backslashes, for example:

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

Or, to avoid the confusion over the fact that the backslash within a normal string literal is escaped with yet another backslash, we can use an extended string delimiter of #" and "#:

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

But, if possible, you really should fix that API that is returning those backslashes, as that's obviously incorrect. The author of that code was apparently under the mistaken impression that forward slashes must be escaped, but this is not true.

Bottom line, the API should be fixed to not insert these backslashes, but until that's remedied, you can use the above to remove any backslashes that may occur.


In the discussion in the comments below, there seems to be enormous confusion about backslashes in strings. So, let's step back for a second and discuss "string literals". As the documentation says, a string literal is:

You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").

Note, a string literal is just a representation of a particular fixed sequence of characters in your code. But, this should not be confused with the underlying String object itself. The key difference between a string literal and the underlying String object is that a string literal allows one to use a backslash as an "escape" character, used when representing special characters (or doing string interpolation). As the documentation says:

String literals can include the following special characters:

  • The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
  • An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point

So, you are correct that in a string literal, as the excerpt you quoted above points out, you cannot have an unescaped backslash. Thus, whenever you want to represent a single backslash in a string literal, you represent that with a \\.

Thus the above stringByReplacingOccurrencesOfString means "look through the string1, find all occurrences of a single backslash, and replace them with an empty string (i.e. remove the backslash)."

Consider:

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"

A little confusingly, if you look at string1 in the "Variables" view of the "Debug" panel or within playground, it will show a string literal representation (i.e. backslashes will appear as "\\"). But don't be confused. When you see \\ in the string literal, there is actually only a single backslash within the actual string. But if you print the value or look at the actual characters, there is only a single backslash in the string, itself.

In short, do not conflate the escaping of the backslash within a string literal (for example, the parameters to stringByReplacingOccurrencesOfString) and the single backslash that exists in the underlying string.

How do I write slash and quote together (e.g. \ ) inside a swift string?

You just need to escape each individual special character you want in the String with a \. In your example it would look like this:

let slashAndQuote = "How to write a slash and quote together, (something like this '\\\"')"
print(slashAndQuote)

This gives an output of:

How to write a slash and quote together, (something like this '\"')

You can do the same for just the slash and quote as well:

let slash = "\\\""


Related Topics



Leave a reply



Submit