简体   繁体   English

Java中的“转义序列”的目的是什么?

[英]What is the purpose of Escape Sequence \' in java?

if I print ' (single quote) in the System.out.println() I can get exact output. 如果我在System.out.println()打印'(单引号),则可以获得准确的输出。

Like : 喜欢 :

System.out.println("test'test");
output:  test'test

What is the purpose of using \\' escape sequence in java? 在Java中使用\\'转义序列的目的是什么?

This also gives me the same output. 这也给了我相同的输出。

 System.out.println("test\'test");
 output:  test'test

pls explain what is the main purpose of \\' escape sequence in java 请说明Java中转义序列的主要目的是什么

It's for use in character literals: 它用于字符文字中:

char c = '\'';

Without that, it would be painful to get a single apostrophe as a char . 没有它,将单个撇号作为char将是很痛苦的。

This is useful for character literals stored in char . 这对于存储在char字符文字很有用。

Imagine you want a character constant to just hold a ' . 想象一下,您希望一个字符常量只保留一个' You could do: 您可以这样做:

public static final char SINGLE_QUOTE = '';

This won't work as it only is an empty character, but we want a single quote. 这将不起作用,因为它只是一个空字符,但我们需要一个单引号。 Hence the escape character \\' . 因此,转义字符\\'

public static final char SINGLE_QUOTE = '\'';

If you print it on System.out.println , you'll see the difference. 如果将其打印在System.out.println ,则会看到不同之处。

For an exercise, try and take your exact example and see if you can print a double quote literal " without escaping it. You'll see it's not possible. You will have to escape it with \\" . 作为练习,请尝试以您的确切示例为例,看看是否可以打印双引号文字"不转义。您将看到不可能。必须用\\"对其进行转义\\"

Reference: String literals and Escape Sequences for Character and String Literals . 参考: 字符串文字字符和字符串 文字的 转义序列

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

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