java基础—String类型常用api

1、字符串比较

equals
equalsIgnoreCase  忽略大小写做比较

2、字符串拆分(切片)

split

String a = "lemon:python:Java";
        //split切片之后的结果是一个一维字符串类型数组
        String[] arr = a.split(":");
        for(int i = 0 ;i <arr.length; i++){
            System.out.println(arr[i]);
        }


3、字符串截取
substring

字符下标从0开始

String  a = "lemon";
        //l  e  m  o  n
        //0  1  2  3  4
  System.out.println(a.substring(2,4));


4、替换
replace

        //特别注意:字符串的值不能被改变 ,改变之后结果保存到新的变量中才可以
        String a = "lemon";
        String b = a.replace("mo","ee");
        System.out.println(b);

5、字符串查找

indexOf
lastIndexOf
contains

> indexOf 返回查找字符所在字符串的位置 -- 索引
> lastIndexOf 返回查找字符所在字符串最后的位置 --索引
> contains 字符串中是否有包含指定的字符串

String a = "lemonban";
        System.out.println(a.lastIndexOf("n"));
        if(a.contains("lemon")){
            System.out.println("包含了lemon字符串");}


6、判断是否以指定字符串开头或结尾
startsWith
endWith

String a ="lemonban";
        if(a.endsWith("ban")){
            System.out.println("字符串是以ban结尾的");
        }

7、字符串拼接
concat

 String a= "lemon";
        System.out.println(a.concat("ban"));
        System.out.println(a+"ban");


8、判空
isEmpty

String a = "lemon";
        System.out.println(a.isEmpty());

9、去掉左右空格

trim

String a= " lemon ";
        String b = "lemon";
        String c = a.trim();
        System.out.println(c.equals(b));

10、字符串长度
length

11、字符串转字节数组
toCharArray

String a = "lemon";
        char[] arr=  a.toCharArray();
        for(int i = 0 ; i<arr.length;i++){
            System.out.println(arr[i]);
        }

12、转大小写
toUpperCase
toLowerCase

 String a = "LEMON";
System.out.println(a.toLowerCase());

 

== 和 equals 区别

== 基本数据类型比较的是值,引用数据类型比较的是地址值。
equals 是Object类中的方法,基本数据类型无法调用。
equals默认使用==号,重写之后一般比较的是内容。

 

猜你喜欢

转载自www.cnblogs.com/erchun/p/13184058.html
今日推荐