反斜杠(\)的行为方式不同 [英] Backslash (\) behaving differently

查看:66
本文介绍了反斜杠(\)的行为方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的小代码

public class Testing {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String firstString = sc.next();
        System.out.println("First String : " + firstString);
        String secondString = "text\\";
        System.out.println("Second String : " + secondString);
    }
}

当我输入为 text \\ 时,我的输出为

When I provide input as text\\ I get output as

First String : text\\
Second String : text\

当我提供给第一个字符串的输入与第二个字符串相同时,为什么会得到两个不同的字符串.

Why I am getting two different string when input I provide to first string is same as second string.

推荐答案

在运行时作为输入提供的控制台中的双反斜杠实际上是两个反斜杠.您只需编写两次ASCII字符反斜杠即可.

The double backslash in the console you provide as input on runtime are really two backslashes. You simply wrote two times ASCII character backslash.

字符串文字中的双反斜杠表示仅一个反斜杠.因为您不能在字符串文字中写一个反斜杠.为什么?因为反斜杠是一个特殊字符,用于转义"特殊字符.例如:制表符,换行符,反斜杠,双引号.如您所见,反斜杠也是需要转义的字符之一.你如何逃脱?带反斜杠.因此,通过将反斜杠放在反斜杠后面来完成转义.因此,这导致两个反斜杠.这将被编译为一个反斜杠.

The double backslash inside the string literal means only one backslash. Because you can't write a single backslash in the a string literal. Why? Because backslash is a special character that is used to "escape" special characters. Eg: tab, newline, backslash, double quote. As you see, backslash is also one of the character that needs to be escaped. How do you escape? With a backslash. So, escaping a backslash is done by putting it behind a backslash. So this results in two backslashes. This will be compiled into a single backslash.

您为什么必须转义字符?查看以下字符串:此是"字符串.如果要使用Java将其编写为字符串文字,则可能会故意认为它看起来像这样:

Why do you have to escape characters? Look at this string: this "is" a string. If you want to write this as a string literal in Java, you might intentionally think that it would look like this:

String str = "this "is" a string";

如您所见,它将无法编译.所以像这样逃避他们:

As you can see, this won't compile. So escape them like this:

String str = "this \"is\" a string";

现在,编译器知道"不会关闭字符串,但实际上意味着字符" ,因为您使用反斜杠对其进行了转义.

Right now, the compiler knows that the " doesn't close the string but really means character ", because you escaped it with a backslash.

这篇关于反斜杠(\)的行为方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆