简体   繁体   English

如何创建一个带有“字符”的字符串?(Java)

[英]How do I make a string with a " character in it? (Java)

那几乎是我的问题,我需要做这样的事情:

String scriptContent = "print("Hello World")";

使用\\"

String scriptContent = "print(\"Hello World\")";

You're looking for something called an escape sequence , which is a way of telling Java to interpret a particular character as something other than what it means by default. 您正在寻找一种称为转义序列的东西,这是一种告诉Java将特定字符解释为默认情况下的其他内容的方法。 In your case, you can make a Java string containing a double-quote by prefixing it with a slash: 在您的情况下,您可以通过在其前面添加斜杠来创建包含双引号的Java字符串:

String scriptContent = "print(\"Hello World\")";

There are many other escape sequences in Java. Java中还有许多其他转义序列。 For example, \\\\ stands for a slash character itself (instead of the start of another escape sequence!); 例如, \\\\代表斜杠字符本身(而不是另一个转义序列的开头!); \\' stands for a single quote; \\'代表单引号; and \\n stands for a newline. \\n代表换行符。 There are many others; 还有很多其他的; consult a Java reference for more details. 有关更多详细信息,请参阅Java参考。

您可以使用转义字符来执行此操作

String scriptContent = "print(\"Hello World\")";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM