04-字符串和包装类

2019-05-24  本文已影响0人  北街九条狗

复习要点

1.字符串

1.1String类
// String类代表一组字符串常量,对其所有修改都是在原有基础上进行的
// String是引用数据类型,但与一般对象不同,字符串保存在字符串常量池中
public class StringDemo{
    public static void main(String[] args) {
        String str = "hello";
    }
}
1.2字符串常用方法

equals 比较字符串是否一样

public class Demo1 {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "hello";
        System.out.println(str1 == str2);// true,因为str1和str2都指向常量池
        System.out.println(str1.equals(str2));// true
    }
}
public class Demo2 {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = new String("hello");
        System.out.println(str1 == str2);// false,因为str1指向常量池,str2指向堆
        System.out.println(str1.equals(str2));// true
    }
}

substring 截取字符串

public class Demo {
    public static void main(String[] args) {
        String str1 = "helloworld";
        System.out.println(str1.substring(2,4));// ll
        // 提示:substring方法是截取后返回一个新字符串,并没有改变str1的值
        System.out.println(str1);//helloworld
        // 除非重新赋值
        str1 = str1.substring(2,4);
        System.out.println(str1);// ll
    }
}
public class Demo {
    public static void main(String[] args) {
        String str1 = "helloworld";
        System.out.println(str1.substring(2));// lloworld,只写一个参数,默认截取到最后
    }
}

indexOf/lastIndexOf 查找字符串第一次/最后一次出现的索引值

public class Demo {
    public static void main(String[] args) {
        String str1 = "helloworld";
        System.out.println(str1.indexOf("o")); // 4
        System.out.println(str1.lastIndexOf("o")); // 6
    }
}

split 将字符串分割成一个数组

public class Demo {
    public static void main(String[] args) {
        String str1 = "黑桃;红桃;方块;草花";
        String str[] = str1.split(";"); // str长度为4 {黑桃,红桃,方块,草花}
    }
}

charAt 返回指定索引处的字符

public class Demo {
    public static void main(String[] args) {
        String str1 = "helloworld";
        System.out.println(str.charAt(1)); // e
    }
}

startsWith/endsWith 是否以某子串开始/结束

public class Demo {
    public static void main(String[] args) {
        String str1 = "今天是个好日子";
        System.out.println(str1.startsWith("今天"));// true
        System.out.println(str1.startsWith("后天"));// false
        System.out.println(str1.endsWith("日子"));// true
        System.out.println(str1.endsWith("月子"));// false
    }
}

经典练习题

1.在一个字符串中查找另一个字符串出现的次数(查单词)

2.输出1,2,2,3,4,5能组成的所有6位数组合

3.字符串与包装类之间的转换

上一篇 下一篇

猜你喜欢

热点阅读