Swift 2.0 Escaping string for new line (String Encoding) - string

I am trying to escape string for new line i.e \n.
For example lets say string is:-
First Line Of String
second Line of String
Third Line of String
Now if i use String extension and say
func escapeString() -> String{
newString = self.stringByRemovingPercentEncoding
return newString
}
This extension does not give me newString as
First Line Of String\nSecond Line Of String\nThird Line Of String
I need above string as a jsonString to pass to server.i.e. i have to String encode it

Swift 5
You can use JSONEncoder to escape \n, \, \t, \r, ', " and etc. characters instead of manually replacing them in your string e.g.:
extension String {
var escaped: String {
if let data = try? JSONEncoder().encode(self) {
let escaped = String(data: data, encoding: .utf8)!
// Remove leading and trailing quotes
let set = CharacterSet(charactersIn: "\"")
return escaped.trimmingCharacters(in: set)
}
return self
}
}
let str = "new line - \n, quote - \", url - https://google.com"
print("Original: \(str)")
print("Escaped: \(str.escaped)")
Outputs:
Original: new line -
, quote - ", url - https://google.com
Escaped: new line - \n, quote - \", url - https:\/\/google.com

stringByRemovingPercentEncoding is for percent encoding as used in URLs, as you might expect from the name. (If not from that, maybe from reading the docs, the pertinent part of which even shows up in Xcode code completion.) That is, it takes a string like "some%20text%20with%20spaces" and turns it into "some text with spaces".
If you want to do a different kind of character substitution, you'll need to do it yourself. But that can still be a one-liner:
extension String {
var withEscapedNewlines: String {
return self.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
}
}
Note the first argument to self.stringByReplacingOccurrencesOfString is an escape code passed to the Swift compiler, so the actual value of the argument is the newline character (ASCII/UTF8 0x0A). The second argument escapes the backslash (in the text passed to the Swift compiler), so the actual value of the argument is the text \n.

Related

Read A String Exactly As It Is in Haskell

My program is something like that:
func = do
text <- getLine
return text
If I read line \123\456, the result is, naturally, \\123\\456.
How can I obtain \123\456 as the result?
Based on the discussion in comments, it looks like you want to parse the string as if it was a string literal, except that it is not surrounded by quotes.
We can make use of of read :: Read a => String -> a here that for a string parses it as if it was a string literal to a string. The only problem is that this string literal is surrounded by double quotes (").
We can thus add these quotes, and work with:
read ('"' : text ++ "\"") :: String
Not every string text is however per se a valid string literal, so the above might fail. For example if the text contains a double quote itself, that is not directly preceded by a backslash (\).

Golang trimPrefix from string "\"

I've seen that golang have the function func TrimPrefix(s, prefix string) string which returns s without the provided leading prefix string.
My problem is that I have a string which start with the character "\" (for example "\foo"). When I try to use TrimPrefix I getting an error.
golang code:
var s = "\foo"
s = strings.TrimPrefix(s, "\")
fmt.Print(s)
error:
./prog.go:10:32: newline in string
./prog.go:10:32: syntax error: unexpected newline, expecting comma or )
I have seen that it is due to golang understang "\" as the scape character. Do you know if ther is any golang option I can use in order to make golang understand that I don't want to use "\" as the escape character?
"\" is not a valid Go string literal. What you get is a compile-time error. In interpreted string literals backslash \ is a special character.
If you want the string to contain a backslash character, you have to use the sequence \\:
var s = "\\foo"
s = strings.TrimPrefix(s, "\\")
Which will output (try it on the Go Playground):
foo
Another option is to use raw string literals where the backslash is not special:
var s = `\foo`
s = strings.TrimPrefix(s, `\`)
Try this one on the Go Playground.
if you only want to trim the prefix which is a specific prefix( like "\" is a prefix with length of 1 ), you can use slice function as :str[len(prefix):].
Just because it is a prefix -- head of a string and a length-known prefix.
Ignore my post if you only want to know the use of TrimPrefix. :D

How to put double quotes into Swift String

I am writing some codes that deals with string with double quote in Swift. Here is what I've done so far:
func someMethod {
let string = "String with \"Double Quotes\""
dealWithString(string)
}
func dealWithString(input: String) {
// I placed a breakpoint here.
}
When I run the codes the breakpoint stopped there as usual but when I input the following into the debugger:
print input
This is what I get:
(String) $R0 = "String with \"Double Quotes\""
I got this string with the backslashes. But if I tried to remove the backslashes from the source, it will give me compile error. Is there a workaround for this?
You are doing everything right. Backslash is used as an escape character to insert double quotes into Swift string precisely in the way that you use it.
The issue is the debugger. Rather than printing the actual value of the string, it prints the value as a string literal, i.e. enclosed in double quotes, with all special characters properly escaped escaped.
If you use print(input) in your code, you would see the string that you expect, i.e. with escape characters expanded and no double quotes around them.
Newer versions of Swift support an alternate delimiter syntax that lets you embed special characters without escaping. Add one or more # symbols before and after the opening and closing quotes, like so:
#"String with "Double Quotes""#
Be careful, though, because other common escapes require those extra # symbols, too.
#"This is not a newline: \n"#
#"This is a newline: \#n"#
You can read more about this at Extended String Delimiters at swift.org.
extension CustomStringConvertible {
var inspect: String {
if self is String {
return "\"\(self)\""
} else {
return self.description
}
}
}
let word = "Swift"
let s = "This is \(word.inspect)"

How do I write a multi-line string in Rust? [duplicate]

This question already has answers here:
What is the syntax for a multiline string literal?
(5 answers)
Closed 1 year ago.
Is it possible to write something like:
fn main() {
let my_string: &str = "Testing for new lines \
might work like this?";
}
If I'm reading the language reference correctly, then it looks like that should work. The language ref states that \n etc. are supported (as common escapes, for inserting line breaks into your string), along with "additional escapes" including LF, CR, and HT.
Another way to do this is to use a raw string literal:
Raw string literals do not process any escapes. They start with the
character U+0072 (r), followed by zero or more of the character U+0023
(#) and a U+0022 (double-quote) character. The raw string body can
contain any sequence of Unicode characters and is terminated only by
another U+0022 (double-quote) character, followed by the same number
of U+0023 (#) characters that preceded the opening U+0022
(double-quote) character.
All Unicode characters contained in the raw string body represent
themselves, the characters U+0022 (double-quote) (except when followed
by at least as many U+0023 (#) characters as were used to start the
raw string literal) or U+005C (\) do not have any special meaning.
Examples for string literals:
"foo"; r"foo"; // foo
"\"foo\""; r#""foo""#; // "foo"
"foo #\"# bar";
r##"foo #"# bar"##; // foo #"# bar
"\x52"; "R"; r"R"; // R
"\\x52"; r"\x52"; // \x52
If you'd like to avoid having newline characters and extra spaces, you can use the concat! macro. It concatenates string literals at compile time.
let my_string = concat!(
"Testing for new lines ",
"might work like this?",
);
assert_eq!(my_string, "Testing for new lines might work like this?");
The accepted answer with the backslash also removes the extra spaces.
Every string is a multiline string in Rust.
But if you have indents in your text like:
fn my_func() {
const MY_CONST: &str = "\
Hi!
This is a multiline text!
";
}
you will get unnecessary spaces. To remove them you can use indoc! macros from indoc crate to remove all indents: https://github.com/dtolnay/indoc
There are two ways of writing multi-line strings in Rust that have different results. You should choose between them with care depending on what you are trying to accomplish.
Method 1: Dangling whitespace
If a string starting with " contains a literal line break, the Rust compiler will "gobble up" all whitespace between the last non-whitespace character of the line and the first non-whitespace character of the next line, and replace them with a single .
Example:
fn test() {
println!("{}", "hello
world");
}
No matter how many literal (blank space) characters (zero or a hundred) appear after hello, the output of the above will always be hello world.
Method 2: Backslash line break
This is the exact opposite. In this mode, all the whitespace before a literal \ on the first line is preserved, and all the subsequent whitespace on the next line is also preserved.
Example:
fn test() {
println!("{}", "hello \
world");
}
In this example, the output is hello world.
Additionally, as mentioned in another answer, Rust has "raw literal" strings, but they do not enter into this discussion as in Rust (unlike some other languages that need to resort to raw strings for this) supports literal line breaks in quoted content without restrictions, as we can see above.

Issue with \ and \\ when calling String Split()

I am trying to split some string on the basis of newline character '\n'
I have this delimiter stored in resx file as:
Name: RecordDelimiter
Value: \n
When I retrieve this value from .resx file it is always returned as '\n' and
split function does not return accurate results.
However when I try with string "\n", it's working fine
Here is my code -
private static void GetRecords()
{
string recordDelimiter = #"\n";
string recordDelimiter1 = "\n"; // only this returns correct result
string recordDelimiter2 = ResourceFile.RecordDelimiter; //from resx file, returns \\n :-(
string recordDelimiter3 = ResourceFile.RecordDelimiter.Replace("\\", #"\"); //try replacing \\n with \n
string fileOutput = "aaa, bbb, ccc\naaa1, bbb1, ccc1\naaa2, bbb2, ccc2";
string[] records = fileOutput.Split(new string[] { recordDelimiter }, StringSplitOptions.None);
string[] records1 = fileOutput.Split(new string[] { recordDelimiter1 }, StringSplitOptions.None);
string[] records2 = fileOutput.Split(new string[] { recordDelimiter2 }, StringSplitOptions.None);
string[] records3 = fileOutput.Split(new string[] { recordDelimiter3 }, StringSplitOptions.None);
int recordCount = records.Count(); //returns 1
int recordCount1 = records1.Count(); //returns 3 -- only this returns correct result
int recordCount2 = records2.Count(); //returns 1
int recordCount3 = records3.Count(); //returns 1
}
I want to keep the delimiter in resx file.
Can anyone please guide if I am missing something?
Thank you!
The reason your second method is the only one returning the correct result is that it is the only one where the delimiter is the new line character. "\n" is just a representation of the newline character in C#, and #"\n" is the literal string of a slash followed by the letter n. In other words #"\n" != "\n".
So if you wanted to store the delimiter character in resx, you would need to show us the code of how you are storing it there. Currently it seems to just be stord as a literal string, and not the actual control characters.
One (very rough) fix would be to take the string from the Resources and call .Replace(#"\n", "\n") depending on what exactly is stored in the file. I will update my answer if/when I find a better solution, or once you have updated your question.
EDIT:
Ok, found a somewhat gimmicky solution. The core problem is how do you write just \n, correct? Well, I made a test project, with a textbox and the following code:
this.textBox1.Text = "1\n2";
Fire up this project, select all of the text in the textbox, and copy to clipboard. Then go to your real project's resources, and paste the value from your clipboard. Then carefully delete the numbers from around the control character. And there you go, \n control character in a resource string. (The reason for the numbers was that it wasn't possible to select only the control character from the textbox.)

Resources