JavaSE:10、字符串

1、String类

初始化
使用双引号创建的字符串,如果内容相同,那么都是同一个对象
用equals判断字符是否一样
import com.test.*;

public class Main {
    public static  void main(String [] argv)
    {
        String s="hello";
        String s1=new String("hello");
        String s2="hello";
        //==  判断是否同一个对象
        System.out.println(s==s2);//true
        System.out.println(s1==s2);//false
        System.out.println(s1.equals(s2));//true
    }
}
常用方法:
import com.test.*;

public class Main {
    public static  void main(String [] argv)
    {
        String s="hello";
      String s1="how are you";

        System.out.println(s.length());//5
        System.out.println("world".length());//5
        System.out.println(s.substring(0,3));//hel
        System.out.println(s.substring(s.length()-2,s.length()));//lo

        String s2[]=s1.split(" ");
        for(String i:s2)
            System.out.print(i+"---");//how---are---you---
        System.out.println();

        char c[]=s.toCharArray();
        System.out.println(c);//hello
        String s3=new String(c);
        System.out.println(s3);//hello


    }
}
import com.test.*;

public class Main {
    public static  void main(String [] argv)
    {
        String str = "Hello world!";
       //第一次出现位置
        System.out.println(str.indexOf("world"));        // 6
        //下标3开始l第一次出现位置
        System.out.println( str.indexOf("l", 3));//3
        //转换为字符串
        System.out.println(123);//123
        //是否空
        System.out.println(str.isEmpty());//false
        //转换为char类型
        char c=str.charAt(3);//下标
        System.out.println(c);


    }
}

2、StringBuilder类

用于字符串处理,进行优化,减少字符对象的建立
import com.test.*;

public class Main {
    public static  void main(String [] argv)
    {
        String s1="1";
        String s2="2";
        String s3="3";
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(s1).append(s2).append(s3);
        System.out.println(stringBuilder);//123
        
    }
}
import com.test.*;

public class Main {
    public static  void main(String [] argv)
    {
        String s1="1";
        String s2="2";
        String s3="3";
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(s1).append(s2).append(s3);

        String str=stringBuilder.toString();
        System.out.println(str); //123
        stringBuilder.delete(1,2);
        System.out.println(stringBuilder);//13


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值