简体   繁体   English

String.length()函数

[英]String.length() function

Can somebody please explain me this behavior of java. 有人可以向我解释一下Java的这种行为。

class StringLength {
    public static void main(String args[]) {
        String str = "Hi! This is me.";
        int length = str.length();
        System.out.println("String length is :" + length);
        System.out.println("String length for second case is :".length());

    }
}

The output of code is : 代码输出为:

String length is :15 字符串长度是:15

34 34

First println statement gives output as 15. That's ok, but what about second one?? 第一个println语句的输出为15。没关系,但是第二个语句呢? How second one is even syntactically correct, because concatenation operator for java is "+" not ".". 第二个语法在语法上是正确的,因为java的串联运算符是“ +”而不是“。”。 can anyone please explain me this output. 谁能解释一下这个输出。

The second one is synonymous to: 第二个是同义词:

String str2 = "String length for the second case is:";
System.out.println(str2.length());

You are calling the length() method on the string "String length for second case is :" The characters in that string add up to 34. 您在字符串"String length for second case is :"上调用length()方法,该字符串中的字符加起来为34。

It would be the same as saying 就像说一样

String s = "String length for second case is :"; String s =“第二种情况的字符串长度为:”;

System.out.println( s.length() ); System.out.println(s.length());

When running this code, I get 运行此代码时,我得到

String length is :15
34

Sure, the length of "Hi! This is me." 当然,长度是"Hi! This is me." is 15. But "String length for second case is :" is a String literal, which can be treated as a String object, and a method can be called on it too. 是15。但是"String length for second case is :"是一个String文字,可以将其视为String对象,也可以在其上调用方法。 There is no concatenation; 没有串联; just a method call on a string literal. 只是对字符串文字的方法调用。 Its length is 34. 长度为34。

System.out.println("String length for second case is :".length());

打印字符串"String length for second case is :" 34。

The second one calls method of the string literal "String length for second case is :". 字符串文字“第二种情况的字符串长度为:”的第二个调用方法。

It's equivalent to: 等效于:

String str2 = "String length for second case is :";
System.out.println( str2.length() );

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

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