创建字符串对象
String类包含许多可用于创建String对象的构造函数。默认构造函数创建一个空字符串作为其内容的String对象。
例如,以下语句创建一个空的String对象,并将其引用分配给emptyStr变量:
String emptyStr = new String();
String类包含一个构造函数,它接受另一个String对象作为参数。
String str1 = new String();
String str2 = new String(str1); // Passing a String as an argument
现在str1与str2表示相同的字符序列。 在上面的示例代码中,str1和str2都代表一个空字符串。也可以传递一个字符串字面量到这个构造函数。
String str3 = new String("");
String str4 = new String("Learn to use String !");
在执行这两个语句之后,str3将引用一个String对象,该对象将一个空字符串作为其内容,str4将引用一个String对象,它将“Learn to use String !” 作为其内容。
字符串的长度
String类包含一个length()方法,该方法返回String对象中的字符数。length()方法的返回类型是int。空字符串的长度为零。叁考以下示例 -
public class Main {
public static void main(String[] args) {
String str1 = new String();
String str2 = new String("Hello,String!");
// Get the length of str1 and str2
int len1 = str1.length();
int len2 = str2.length();
// Display the length of str1 and str2
System.out.println("Length of \"" + str1 + "\" = " + len1);
System.out.println("Length of \"" + str2 + "\" = " + len2);
}
}
上面的代码生成以下结果。
Length of "" = 0
Length of "Hello,String!" = 13
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。