在 Java 中,有没有办法编写字符串文字而不必转义引号? [英] In Java, is there a way to write a string literal without having to escape quotes?
问题描述
假设你有一个字符串文字,里面有很多引号.你可以全部避开它们,但这很痛苦,而且难以阅读.
Say you have a String literal with a lot of quotation marks inside it. You could escape them all, but it's a pain, and difficult to read.
在某些语言中,您可以这样做:
In some languages, you can just do this:
foo = '"Hello, World"';
然而,在Java中,''
用于char
s,所以你不能以这种方式将它用于String
s.某些语言具有解决此问题的语法.例如,在python中,你可以这样做:
In Java, however, ''
is used for char
s, so you can't use it for String
s this way. Some languages have syntax to work around this. For example, in python, you can do this:
"""A pretty "convenient" string"""
Java 有没有类似的东西?
Does Java have anything similar?
推荐答案
答案是否定的,证据在 Java 语言规范:
The answer is no, and the proof resides in the Java Language Specification:
StringLiteral:
"StringCharacters"
StringCharacters:
StringCharacter
| StringCharacters StringCharacter
StringCharacter:
InputCharacter but not " or
| EscapeSequence
如您所见,StringLiteral
只能由 "
绑定,并且不能包含没有转义的特殊字符..
As you can see a StringLiteral
can just be bound by "
and cannot contain special character without escapes..
附注:您可以在项目中嵌入 Groovy,这将扩展 Java 的语法,允许您使用 '''多行字符串 '''
、'带单引号的字符串"'
以及 带 ${variable} 的字符串"
.
A side note: you can embed Groovy inside your project, this will extend the syntax of Java allowing you to use '''multi line string '''
, ' "string with single quotes" '
and also "string with ${variable}"
.
这篇关于在 Java 中,有没有办法编写字符串文字而不必转义引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!