java个人学习笔记-13(String 类)

创建字符串

String  a = "hello";

String 类是不可改变的,一旦创建了 String 对象,那它的值就无法改变了

字符串长度

用于获取有关对象的信息的方法称为访问器方法。

String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。

例子:

public class Aa{
        public static void main(String args[]){
                String a = "hello java!!!";
                int len = a.length();
                System.out.println("a的长度为:" + len);
        }
}

输出结果:

a的长度为:13

连接字符串

String 类提供了连接两个字符串的方法:

  • string1.concat(string2);
  • 使用’+'操作符来连接字符串

例子:

public class Aa{
        public static void main(String args[]){
                String s1 = "hello ";
                String s2 = "world";
                String s3 = "!!!";
                String s = s1.concat(s2) + s3;
                System.out.println(s);
        }
}

输出结果:

hello world!!!

创建格式化字符串

输出格式化数字可以使用 printf() 和 format() 方法
例子:

public class Aa{
        public static void main(String args[]){
                int i = 10;
                double f = 3.14;
                String s = "hello";
                System.out.printf("整数:%d,浮点数:%f,字符串:%s\n",i,f,s);
                String fs = String.format("整数:%d,浮点数:%f,字符串:%s",i,f,s);
                System.out.println(fs);
        }
}

输出结果:

整数:10,浮点数:3.140000,字符串:hello
整数:10,浮点数:3.140000,字符串:hello
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值