Difference between single and double quotes in Flutter/Dart - string

I know that single and double quotes have at least some level of equivelence in Dart. For example,
var myString = "Hello world"; // double quotes
and
var myString = 'Hello world'; // single quotes
have no programmatic difference to my knowledge.
I keep seeing them used seemingly interchangeably in various examples and in some documentation. I'm wondering if there is a subtle difference that I am missing or if there is a recommended style to follow, especially in Flutter.
This is a Q&A self answer after reading the Flutter and Dart style guides.

Single and double quotes both work in Dart
final myString = 'hello';
is the same as
final myString = "hello";
Delimiters need to be escaped
Use a \ backslash to escape single quotes in a single quote string.
final myString = 'Bob\'s dog'; // Bob's dog
Same thing to escape double quotes in a double quote string.
final myString = "a \"quoted\" word"; // a "quoted" word
But no need to escape anything if the delimiter is different.
final myString = "Bob's dog"; // Bob's dog
final myString = 'a "quoted" word'; // a "quoted" word
Also no need to worry about the value passed into an interpolated string.
final value = '"quoted"'; // "quoted"
final myString = "a $value word"; // a "quoted" word
Prefer single quotes in Flutter
The Flutter style guide recommends using single quotes for everything
final myString = 'hello';
except for nested strings
print('Hello ${name.split(" ")[0]}');
or strings containing single quotes (optional)
final myString = "Bob's dog";
final myString = 'Bob\'s dog'; // ok
The Dart style guide appears to be silent on the issue.

Related

Splitting a string over multiple lines with no extra whitespaces using Groovy?

Lets say I have a long string, and putting it on one line would decrease the readability.
This is would be the solution and it works:
def string = "This is a very\
long string"
But what if im in a Method or an if Statement were the lines are already indented. Then i would have to put the second part of the string like this which isnt very readable.
if (condition) {
def string = "This is a very\
long string"
}
How can i make the output look like this:
This is a very long string
With something like this:
if (condition) {
def string = "This is a very\
long string"
}
If you would want to have the line breaks, there is stripMargin to
help with removal of leading white space (at least until groovy supports
the new multi-line string literals from Java).
But since you don't want the line breaks, I'd just "add" the strings.
This usually is a no-no, because strings are immutable in java and this
will create intermediate instances. Yet then the compiler
should be able to optimize that, if you just add up string
literals (the (dynamic) groovy compiler 4.x does not). But then again,
it might not matter. And if you only want to pay once, make that
a public static final String MY_CONST_STRING = ... somewhere.
if (1) {
println "This is a very " +
"long string " +
"and more"
}
How can i make the output look like this:
This is a very long string
The code you show in the question is an idiomatic way to do it if you really need/want the literal definition to span lines in the source file without including a newline character in the literal:
def string = "This is a very \
long string"
You could also do something like this:
def string = '\
this is a \
very long string.'

How to wrap a raw string literal without inserting newlines into the raw string?

I have a raw string literal which is very long. Is it possible to split this across multiple lines without adding newline characters to the string?
file.write(r#"This is an example of a line which is well over 100 characters in length. Id like to know if its possible to wrap it! Now some characters to justify using a raw string \foo\bar\baz :)"#)
In Python and C for example, you can simply write this as multiple string literals.
# "some string"
(r"some "
r"string")
Is it possible to do something similar in Rust?
While raw string literals don't support this, it can be achieved using the concat! macro:
let a = concat!(
r#"some very "#,
r#"long string "#,
r#"split over lines"#);
let b = r#"some very long string split over lines"#;
assert_eq!(a, b);
It is possible with indoc.
The indoc!() macro takes a multiline string literal and un-indents it at compile time so the leftmost non-space character is in the first column.
let testing = indoc! {"
def hello():
print('Hello, world!')
hello()
"};
let expected = "def hello():\n print('Hello, world!')\n\nhello()\n";
assert_eq!(testing, expected);
Ps: I really think we could use an AI that recommend good crates to Rust users.

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)"

groovy replace double quotes with single and single with double

I have a string "['type':'MultiPolygon', 'coordinates':[[73.31, 37.46], [74.92, 37.24]]]"
How can I replace all single quotes with double quotes and double to with single?
The result should be like this:
'["type":"MultiPolygon", "coordinates":[[73.31, 37.46], [74.92, 37.24]]]'
From link given by #yate, you can find a method:
tr(String sourceSet, String replacementSet)
and apply that to your string as:
def yourString = ...
def changedString = yourString.tr(/"'/,/'"/)
that will do the job.
You want to use the replaceAll method. Since the first conversion will be overridden by the second, you may need a temporary variable:
String replacePlaceholder = '%%%' // Some unlikely-to-occur value
yourString = yourString.replaceAll('\'', replacePlaceholder)
.replaceAll('"', '\'')
.replaceAll(replacePlaceholder, '"')
It's certainly not the most efficient way to do it, but it's a start.

What's the difference of strings within single or double quotes in groovy?

def a = "a string"
def b = 'another'
Is there any difference? Or just like javascript to let's input ' and " easier in strings?
Single quotes are a standard java String
Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String. For example:
println 'hi'.class.name // prints java.lang.String
println "hi".class.name // prints java.lang.String
def a = 'Freewind'
println "hi $a" // prints "hi Freewind"
println "hi $a".class.name // prints org.codehaus.groovy.runtime.GStringImpl
If you try templating with single quoted strings, it doesn't do anything, so:
println 'hi $a' // prints "hi $a"
Also, the link given by julx in their answer is worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.
My understanding is that double-quoted string may contain embedded references to variables and other expressions. For example: "Hello $name", "Hello ${some-expression-here}". In this case a GString will be instantiated instead of a regular String. On the other hand single-quoted strings do not support this syntax and always result in a plain String. More on the topic here:
http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings
I know this is a very old question, but I wanted to add a caveat.
While it is correct that single (or triple single) quotes prevent interpolation in groovy, if you pass a shell command a single quoted string, the shell will perform parameter substitution, if the variable is an environment variable. Local variables or params will yield a bad substitution.

Resources