问题
What is the string literal \\\\
backslash? What does it do? I have thought about it but I do not understand it. I also read it on wikipedia. When I try to print the following:
System.out.println(\"Mango \\\\ Nightangle\");
the output is: Mango \\ Nightangle
What is the significance of this string literal?
回答1:
\
is used as for escape sequence in many programming languages, including Java.
If you want to
- go to next line then use
\n
or\r
, - for tab use
\t
- likewise to print a
\
or"
which are special in string literal you have to escape it with another\
which gives us\\
and\"
回答2:
Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \"
to represent quotation marks. Then you have a second problem: how to represent \
? Again, out of convention you decide to use \\
instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n
).
回答3:
\
is used for escape sequences in programming languages.\n
prints a newline\\
prints a backslash\"
prints "\t
prints a tabulator\b
moves the cursor one back
回答4:
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
回答5:
The \
on it's own is used to escape special characters, such as \n
(new line), \t
(tabulation), \"
(quotes) when typing these specific values in a System.out.println()
statement.
Thus, if you want to print a backslash, \
, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\
yields \
.
回答6:
If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.
Console.WriteLine(@"Mango \ Nightangle");
Don't you just wish Java had something like this ;-)
来源:https://stackoverflow.com/questions/12091506/what-is-the-backslash-character