Java字符串创建和长度

创建字符串对象

String类包含许多可用于创建String对象的构造函数。默认构造函数创建一个空字符串作为其内容的String对象。

例如,以下语句创建一个空的String对象,并将其引用分配给emptyStr变量:

String  emptyStr = new String();

  
  
Java

String类包含一个构造函数,它接受另一个String对象作为参数。

String str1 = new String();
String str2 = new String(str1); // Passing a  String as  an  argument

  
  
Java

现在str1str2表示相同的字符序列。 在上面的示例代码中,str1str2都代表一个空字符串。也可以传递一个字符串字面量到这个构造函数。

String str3 = new String("");
String str4 = new String("Learn to use String !");

  
  
Java

在执行这两个语句之后,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);
  }
}

  
  
Java

上面的代码生成以下结果。

Length of  "" = 0
Length of  "Hello,String!" = 13
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值