有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我不需要在字符串声明中转义像\037这样的ASCII字符?

我知道“”是Java中的转义字符。所以我的理解是,每当我声明一个包含特殊字符的字符串时,我都需要用“”对其进行转义。例如:

String backSlash = "\\";

我必须为ascii字符\037创建一个字符串,显然我不需要用“”对其进行转义

String delimiter = "\037"; // enough                                   
String delimiter = "\\037"; // not needed and wrong

为什么呢


共 (2) 个答案

  1. # 1 楼答案

    你在写一篇octal number

    An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

    如果写为“037”,它稍后将被解释为“0”“3”“7”

  2. # 2 楼答案

    My understanding is that whenever I declare a string which contain special characters I need to escape it by "\"

    您的理解是不完整的:Java字符串文本中的反斜杠\可以引入转义序列one of three types

    • 特殊字符转义-这包括\b\t\n\f\r\'\"\\
    • Unicode转义-以\u开头并最多有四个十六进制数字的序列
    • 八进制转义-以\开头的序列,八进制数介于0和377之间8以0开头

    您的示例具有第三种序列(八进制)