在 Java 中,有没有办法编写字符串文字而不必转义引号? [英] In Java, is there a way to write a string literal without having to escape quotes?

查看:26
本文介绍了在 Java 中,有没有办法编写字符串文字而不必转义引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个字符串文字,里面有很多引号.你可以全部避开它们,但这很痛苦,而且难以阅读.

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中,''用于chars,所以你不能以这种方式将它用于Strings.某些语言具有解决此问题的语法.例如,在python中,你可以这样做:

In Java, however, '' is used for chars, so you can't use it for Strings 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆