本文介绍了Java 中的三重引号,如 Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,您可以执行以下操作:

In Scala you can do something like this:

val expr = """ This is a "string" with "quotes" in it! """

Java 中有这样的东西吗?我讨厌使用 "\"" 来表示带引号的字符串.尤其是在 JSON 中组合键/值对时.恶心!

Is there something like this in Java? I abhor using "\"" to represent strings with quotes in them. Especially when composing key/value pairs in JSON. Disgusting!

推荐答案

除了使用 \" 在字符串文字中包含双引号之外,没有其他好的选择.

There is no good alternative to using \" to include double-quotes in your string literal.

有不好的选择:

  • 使用 \u0022,这是双引号字符的 Unicode 转义符.编译器将 Unicode 转义视为键入该字符.它被视为源代码中的双引号字符,结束/开始String文字,因此这不起作用.
  • 连接字符'"',例如"This is a " + '"' + "string".这会起作用,但它似乎比仅使用 \" 更难看且可读性更低.
  • 连接 char 34 以表示双引号字符,例如"这是一个" + (char) 34 + "string".这会起作用,但更不明显的是您试图在字符串中放置双引号字符.
  • 复制并粘贴 Word 的智能引号",例如这是一个带有引号"的字符串"!".这些不是相同的字符(Unicode U+201C 和 U+201D);它们有不同的外观,但它们会起作用.
  • Use \u0022, the Unicode escape for a double-quote character. The compiler treats a Unicode escape as if that character was typed. It's treated as a double-quote character in the source code, ending/beginning a String literal, so this does NOT work.
  • Concatenate the character '"', e.g. "This is a " + '"' + "string". This will work, but it seems to be even uglier and less readable than just using \".
  • Concatenate the char 34 to represent the double-quote character, e.g. "This is a " + (char) 34 + "string". This will work, but it's even less obvious that you're attempting to place a double-quote character in your string.
  • Copy and paste Word's "smart quotes", e.g. "This is a "string" with "quotes" in it!". These aren't the same characters (Unicode U+201C and U+201D); they have different appearances, but they'll work.

我想隐藏恶心",你可以把它隐藏在一个常量后面.

I suppose to hide the "disgusting"-ness, you could hide it behind a constant.

public static final String DOUBLE_QUOTE = "\"";

然后你可以使用:

String expr = " This is a " + DOUBLE_QUOTE + "string" + DOUBLE_QUOTE + ...;

它比其他选项更具可读性,但仍然不是很可读,而且仍然很丑.

It's more readable than other options, but it's still not very readable, and it's still ugly.

Java 中没有 """ 机制,所以使用转义 \" 是最好的选择.它是最易读的,也是最不丑的.

There is no """ mechanism in Java, so using the escape \", is the best option. It's the most readable, and it's the least ugly.

这篇关于Java 中的三重引号,如 Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 01:31