www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - probably a trivial question...

reply WhatMeWorry <kheaser gmail.com> writes:
I was a little (nicely) surprised that I could use double quotes, 
single quotes, or back ticks in the following line of code.

return s.split(";");  // double quotes
or
return s.split(';');  // single quotes
or
return s.split(`;`);  // back ticks

Does D provide any guidance as to what is preferred or are they 
identical for all intents and purposes?
Oct 13 2022
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
Changing the order of lines...

On 10/13/22 16:43, WhatMeWorry wrote:

 return s.split(';');  // single quotes
That one is a single character and very lightweigth because it's just an integral value. You can't put more than one character within single quotes: ';x' // ERROR
 return s.split(";");  // double quotes
That one is a string, which is the equivalent of the following "fat pointer": struct Array_ { size_t length; char * ptr; } For that reason, it can be seen as a little bit more costly. 'length' happens to be 1 but you can use multiple characters in a string: ";x" // works (Aside: There is also a '\0' character sitting next to the ';' in memory so that the literal can be passed to C functions as-is.) Double-quoted strings have the property of escaping. For example, "\n" is not 2 characters but is "the newline character".
 return s.split(`;`);  // back ticks
They are strings as well but they don't do escaping: `\n` happens to be 2 characters. There is also strings that start with q{ and end with }: auto myString = q{ hello world }; And then there is delimited strings that use any delimiter you choose: auto myString = q"MY_DELIMITER hello world MY_DELIMITER"; Some information here: http://ddili.org/ders/d.en/literals.html#ix_literals.string%20literal Ali
Oct 13 2022
prev sibling parent rassoc <rassoc posteo.de> writes:
On 10/14/22 01:43, WhatMeWorry via Digitalmars-d-learn wrote:
 Does D provide any guidance as to what is preferred or are they identical for
all intents and purposes?
You won't see a difference for this specific example since the split function supports character, string and even range separators. So, use what works best for your use case. But here's the difference between them: Single quotes are for singular characters, 'hello' won't compile while ';' and '\n' (escaped newline) will. Double quotes are string literals, i.e. array of characters, which also allow escape sequences like "\r\n". Back ticks, as well as r"...", are raw or wysiwyg ("what you see is what you get") strings, they do not support escape sequences. They are super useful for regex. import std; void main() { writeln("ab\ncd"); // \n is recognized as a newline character writeln(`ab\ncd`); // `...` and r"..." are equivalent writeln(r"ab\ncd"); } will print: ab cd ab\ncd ab\ncd More info here, if you are interested: https://dlang.org/spec/lex.html#string_literals
Oct 13 2022