如何在 Java 中的字符串变量周围添加双引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46228839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:07:30  来源:igfitidea点击:

How to add double quotes around a String variable in Java?

javastring

提问by gig6

I know how to print double quotes around a String literal in Java, but how do you print them with a String variable? The code below won't compile.

我知道如何在 Java 中围绕字符串文字打印双引号,但是如何使用 String 变量打印它们?下面的代码不会编译。

String upperCasePhrase = capInitials("the initial letters should be capitalized");
System.out.println(\" upperCasePhrase \");

回答by TofferJ

There are actually 2 issues with your code.

您的代码实际上有两个问题。

  1. You need to make sure that \" is a String. This can be done by surrounding it with double quotes like this: "\""

  2. You need to concatenate Strings when printing them by using a +

  1. 您需要确保 \" 是一个字符串。这可以通过用双引号括起来来完成,如下所示: "\""

  2. 使用 a 打印字符串时需要连接字符串 +

Change the last line of code in your question to:

将问题中的最后一行代码更改为:

System.out.println("\"" + upperCasePhrase + "\"");

回答by Andy Turner

You can use single quotes around a char; if you then concatenate that to a String, the charwill automatically be converted to a String:

您可以在char;周围使用单引号 如果然后将其连接到 a Stringchar则将自动转换为 a String

System.out.println('"' + upperCasePhrase + '"');

You may just find this a bit clearer to read than using "\"".

您可能会发现这比使用"\"".

回答by Serj Ardovic

There are special characters reserved for Java language which you cannot explicitly use inside your Strings. Such characters require to be 'escaped' or replaced with an alternative notation:

有一些为 Java 语言保留的特殊字符,您不能在字符串中显式使用这些字符。此类字符需要“转义”或替换为其他符号:

Backspace is replaced with \b

退格被替换为 \b

Newline is replaced with \n

换行符替换为 \n

Tab is replaced with \t

Tab 被替换为 \t

Carriage return is replaced with \r

回车被替换为 \r

Form feed is replaced with \f

换页替换为 \f

Double quote is replaced with \"

双引号替换为\"

Backslash is replaced with \

反斜杠被替换为\