Day11 字符串的一些方法

123 阅读1分钟

字符串创建3+1

String str1=new String();//空
char[] charArray={'A','B','C'}
String str2=new String(charArray);//ABC
byte[] byteArray={97,98,99};
String str3=new String(byteArray);//abc
String char="hello";//hello

字符串常量池,直接写的字符串在常量池中
常用类型中,==进行数值比较;引用类型中,==进行地址值比较
推荐常量字符串.equals("str"),不推荐str.equals("常量字符串")
原因:可能出现空指针异常
equalsIgnoreCase忽略大小写比较

字符串获取:

"hello".length()//5,长度
"hello".concat("world")//helloworld,拼接
"hello".charAt(0)//h,索引对应的字符
"hello".indexOf("l")//2,没有为-1,字符串第一次出现的索引

字符串截取:

"helloworld".substring(5)//world,从索引5开始至结束
"helloworld".substring(4,7)//owo,从索引4开始到索引6

字符串转换:

char[] chars="hello".toCharArray();//转换为char数组
chars[0].sout;//h
byte[] bytes="abc".getBytes();//转换为byte数组
bytes[0].sout;//97
"hello".replace("l","*");//he**o,l转换成*

字符串分割

package d0710;

public class Demo01StringSplit {
    public static void main(String[] args) {
        String str="abc,123,456";
        String[] array = str.split(",");//按","切分
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

字符串分割结果.png
split是一个正则表达式,按"."切分会失败,应该写"\."