1. String类:

A. String的特点

字符串是常量,在创建之后不能更改。其实就是说一旦这个字符串确定了,那么就会在内存区域中就生成了这个字符串。字符串本身不能改变,但str变量中记录的地址值是可以改变的。
String类底层采用的是字符数组:private final char value[];

B. String对象的创建

  • String s1 = "abc";
    在内存中只有一个对象。这个对象在字符串常量池中。
  • String s2 = new String("abc");
    在内存中有两个对象。一个new的对象在堆中,一个字符串本身对象,在字符串常量池中。
  • public ``String(``byte[] bytes``)
    字节数组转成字符串
  • public String(char[] value)
    把字符数组转换成字符串

    C. String类常用方法:

  • 长度:str.length();

  • 访问字符:str.charAt(i);
  • 截取子串:str.substring(int beginIndex[, int endIndex]);
  • 包含子串:contains(String s), startsWith(String prefix), endsWith(String postfix)
  • 查找:返回字符串中第一次出现的索引。如果不存在,返回-1

    1. public int indexOf(int char);
    2. public int indexOf(String str);
    3. public int indexOf(String str, int fromIndex);

    案例:查找子串在一个字符串中出现的次数。

    1. public int showCount(String findStr, String str){
    2. if(findStr==null || findStr.isEmpty()){
    3. return 0;
    4. }
    5. int count = 0;
    6. int index = 0;
    7. while(index = str.indexOf(findStr, index) >= 0){
    8. count++;
    9. }
    10. return count;
    11. }
  • 匹配: boolean match(String re)

  • 替换:

    1. String replace(char searchChar, char newChar);
    2. String replaceFirst(String re, String replaceStr);
    3. String replaceAll(String re, String replaceStr);
  • 拆分: String[] split(String re);

  • String trim()
  • 大小写转换:toLowerCase(), toUpperCase()

    D. String类与基本数据类型转换

  • byte[] 数组:

    • byte[] bytes = {97,98,99,100}; String s = new String(bytes);
    • byte[] bytes = str.getBytes();
  • char[] 数组:
    • String str = new String(chars);
    • char[] chars = str.toCharArray();
  • 数字转字符串:String numStr = String.valueOf(123);
  • 判断一个字符是否是一个数字: Character.isDigit(s.charAt(i));
  • 判读一个字符串是否是一个数字:

    1. try {
    2. Integer.parseInt(string);
    3. } catch (NumberFormatException e) {
    4. return false;
    5. }
    6. return true;

    2. StringBuffer类

    StringBuffer是一个可变的字符序列,底层采用字符数组实现,初始容量为16。

    A. 构造方法:

  • StringBuffer()

  • StringBuffer(String str)

    B. StringBuffer方法:

  • StringBuffer append(), 将任意类型的数据,添加缓冲区

  • append 返回值,写return this
    • 调用者是谁,返回值就是谁
  • delete(int start,int end): 删除缓冲区中字符
    • 开始索引包含,结尾索引不包含
  • insert(int index, 任意类型): 将任意类型数据,插入到缓冲区的指定索引上
  • replace(int start,int end, String str): 将指定的索引范围内的所有字符,替换成新的字符串
  • reverse():将缓冲区中的字符反转
  • String toString(): 继承Object,重写toString()
    • 将缓冲区中的所有字符,变成字符串