I want to convert an existing string to raw string.
like:
String s = "Hello \n World"
I want to convert this s variable to raw string(I want to print exact "Hello \n Wrold")
I need backslash(\) in output. I am trying to fetch string value from rest api. it have bunch of mathjax(latex) formula containing backslash.
Thanks
You are asking for a way to escape newlines (and possibly other control characters) in a string value.
There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode is an adequate substitute.
So, given your string containing a newline, you can convert it to a string containing \n (a backslash and an n) as var escapedString = jsonEncode(string);. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);.
Alternatively, if you only care about newlines, you can just replace them yourself:
var myString = string.replaceAll("\n", r"\n");
I have this escaped string:
\u0414\u043B\u044F \u043F\u0440\u043E\u0434\u0430\u0436\u0438
\u043D\u0435\u0434\u0432\u0438\u0436\u0438\u043C\u043E\u0441\u0442\u0438
If I do:
print('\u0414\u043B\u044F \u043F\u0440\u043E\u0434\u0430\u0436\u0438 \u043D\u0435\u0434\u0432\u0438\u0436\u0438\u043C\u043E\u0441\u0442\u0438');
Console will show me:
Для продажи недвижимости
But if I get escaped 2 times string from the server:
\\u0414\\u043B\\u044F
\\u043F\\u0440\\u043E\\u0434\\u0430\\u0436\\u0438
\\u043D\\u0435\\u0434\\u0432\\u0438\\u0436\\u0438\\u043C\\u043E\\u0441\\u0442\\u0438
And do some replace job:
var result = string.replaceAll(new RegExp(r'\\'), r'\');
Compiler will not decode those characters and will show same escaped string:
print(result);
Console:
\u0414\u043B\u044F \u043F\u0440\u043E\u0434\u0430\u0436\u0438
\u043D\u0435\u0434\u0432\u0438\u0436\u0438\u043C\u043E\u0441\u0442\u0438
How I can remove those redunant slashes?
In string literals in Dart source files, \u0414 is a literal representing a unicode code point, whereas in the case of data returned from the server, you're just getting back a string containing backslashes, us, and digits that looks like a bunch of unicode code point literals.
The ideal fix is to have your server return the UTF-8 string you'd like to display rather than a string that uses Dart's string literal syntax that you need to parse. Writing a proper parser for such strings is fairly involved. You can take a look at unescapeCodeUnits in the Dart SDK for an example.
A very inefficient (not to mention entirely hacky and unsafe for real-world use) means of decoding this particular string would be to extract the string representations of the unicode codepoints with a RegExp parse the hex to an int, then use String.fromCharCode().
Note: the following code is absolutely not safe for production use and doesn't match other valid Dart code point literals such as \u{1f601}, or reject entirely invalid literals such as \uffffffffff.
// Match \u0123 substrings (note this will match invalid codepoints such as \u123456789).
final RegExp r = RegExp(r'\\\\u([0-9a-fA-F]+)');
// Sample string to parse.
final String source = r'\\u0414\\u043B\\u044F \\u043F\\u0440\\u043E\\u0434\\u0430\\u0436\\u0438 \\u043D\\u0435\\u0434\\u0432\\u0438\\u0436\\u0438\\u043C\\u043E\\u0441\\u0442\\u0438';
// Replace each \u0123 with the decoded codepoint.
final String decoded = source.replaceAllMapped(r, (Match m) {
// Extract the parenthesised hex string. '\\u0123' -> '123'.
final String hexString = m.group(1);
// Parse the hex string to an int.
final int codepoint = int.parse(hexString, radix: 16);
// Convert codepoint to string.
return String.fromCharCode(codepoint);
});
let word = "sample string"
let firstLetter = Character(word.substringToIndex(advance(word.startIndex,1)).uppercaseString)
I got the above example from a tutorial. Can anyone know what they mean by "advance" and what is difference between "substringToIndex" and "substringWithRange".
This advance syntax is from Swift 1, it's different now.
Swift 2
let firstLetter = Character(word.substringToIndex(word.startIndex.advancedBy(1)).uppercaseString)
The advancedBy method moves the current index along the String.
With substringToIndex you slice a part of the String, beginning at the start of the String and ending at the index defined by advancedBy.
Here you advance by 1 in the String, so it means that substringToIndex will get the first character from the String.
Swift 3
The syntax has changed again, we now use substring and an index with an offset:
let firstLetter = Character(word.substring(to: word.index(word.startIndex, offsetBy: 1)).uppercased())
substringToIndex
Returns a new string containing the characters of the receiver up to,
but not including, the one at a given index.
Return Value A new string containing the characters of the receiver up to, but not including, the one at anIndex. If anIndex is
equal to the length of the string, returns a copy of the receiver.
substringWithRange
Returns a string object containing the characters of the receiver that
lie within a given range.
Return Value A string object containing the characters of the receiver that lie within aRange.
Special Considerations This method detects all invalid ranges (including those with negative lengths). For applications linked
against OS X v10.6 and later, this error causes an exception; for
applications linked against earlier releases, this error causes a
warning, which is displayed just once per application execution.
For more info detail, you can get in the Apple NSString Class Reference
Your tutorial is outdated. advance was deprecated in Swift 2. Strings in Swift cannot be randomly accessed, i.e. there's no word[0] to get the first letter of the string. Instead, you need an Index object to specify the position of the character. You create that index by starting with another index, usually the startIndex or endIndex of the string, then advance it to the character you want:
let word = "sample string"
let index0 = word.startIndex // the first letter, an 's'
let index6 = word.startIndex.advancedBy(6) // the seventh letter, the whitespace
substringToIndex takes all characters from the left of string, stopping before the index you specified. These two are equivalent:
print("'\(word.substringToIndex(index6))'")
print("'\(word[index0..<index6])'")
Both print 'sample'
I am getting a string for a place name back from an API: "Moe\'s Restaurant & Brewhouse". I want to just have it be "Moe's Restaurant & Brewhouse" but I can't get it to properly format without the \.
I've seen the other posts on this topic, I've tried placeName?.stringByReplacingOccurrencesOfString("\\", withString: "") and placeName?.stringByReplacingOccurrencesOfString("\'", withString: "'"). I just can't get anything to work. Any ideas so I can get the string how I want it without the \? Any help is greatly appreciated, thanks!!
You report that the API is returning "Moe\'s Restaurant & Brewhouse". More than likely you are looking at a Swift dictionary or something like that and it is showing you the string literal representation of that string. But depending upon how you're printing that, the string most likely does not contain any backslash.
Consider the following:
let string = "Moe's"
let dictionary = ["name": string]
print(dictionary)
That will print:
["name": "Moe\'s"]
It is just showing the "string literal" representation. 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
But, note, that backslash before the ' in Moe\'s is not part of the string, but rather just an artifact of printing a string literal with an escapable character in it.
If you do:
let string2 = dictionary["name"]!
print(string2)
It will show you that there is actually no backslash there:
Moe's
Likewise, if you check the number of characters:
print(dictionary["name"]!.characters.count)
It will correctly report that there are only five characters, not six.
(For what it's worth, I think Apple has made this far more confusing than is necessary because it sometimes prints strings as if they were string literals with backslashes, and other times as the true underlying string. And to add to the confusion, the single quote character can be escaped in a string literal, but doesn't have to be.)
Note, if your string really did have a backslash in it, you are correct that this is the correct way to remove it:
someString.stringByReplacingOccurrencesOfString("\\", withString: "")
But in this case, I suspect that the backslash that you are seeing is an artifact of how you're displaying it rather than an actual backslash in the underlying string.
this is maybe stupid question but I'm new to swift and i actually can't figure this out.
I have API which returns url as string "http:\/\/xxx". I don't know how to store URL returned from API in this format. I can't store it to variable because of backslash.
From apple doc:
...string cannot contain an unescaped backslash (\), ...
Is there any way how to store string like this or how remove these single backslashes or how to work with this?
Thank you for every advice.
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.
I found I was having this same issue when trying to encode my objects to JSON. Depending on if you're using the newer JSONEncoder class to parse your JSON and you're supporting a minimum of iOS 13, you can use the .withoutEscapingSlashes output formatting:
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
try encoder.encode(yourJSONObject)
Please check the below code.
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)
I've solved with this piece of code:
let convertedStr = jsonString.replacingOccurrences(of: "\\/", with: "/")
To remove single backslash,try this
let replaceStr = backslashString.replacingOccurrences(of: "\"", with: "")
Include a backslash in a string by adding an extra backslash.