特点:
- 代表字符串。java程序中所有的字符串字面值(如"abc")都作为此类的实例实现。它就是该类的一个对象可以直接打点调方法。
- 字符串是一个常量;他们的值在创建之后值就不能被改变。
- 字符串缓冲区支持可变的字符串。因为String对象是不可变的,所以可以共享。
构造方法:
- public String() 空参构造
- public String (Sting original) 字符串常量转换成字符串
- public String(byte [ ] bytes ) 字符数组转成字符串
- public Sting(bytes[] bytes,int index,int length) 字节数组的一部分转成字符串(index表示的是从第几个索引开始,length表示长度)
- public String(char[] value) 字符数组转换成自字符串
- public String(char[] value,int index,int count) 字符数组的一部分转成字符串(index表示从第几个索引开始,count表示字符数量)
方法:
判断方法:
- public boolean equals(object obj) 比较字符串的内容是否相同,区分大小写。
- public boolean equalsIgnoreCase(String str) 比较字符串内容是否相同,忽略大小写。
- public boolean contains(String str) 判断是否包含传进来的字符串。
- public boolean startwith(String str) 判断是否以传进来的字符串开始。
- public boolean endwith(String str) 判断是否以传进来的字符串结束。
- public boolean isEmpty() 判断是否为空串。
获取功能:
- public int length() 获取字符串的长度。
- public char charAt(int index) 获取指定索引位置的字符
- public int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
- public int indexOf(String str) 返回指定字符串在此字符串中第一次出现处的索引。
- public int indexOf(int ch,int fromIndex)返回指定字符在此字符串中从指定位置后第一次出现处的索引。
- public int indexOf(String str,int fromIndex)返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
- public String substring(int start): 从指定位置开始截取字符串,默认到末尾。
- public String substring(int start,int end): 从指定位置开始到指定位置结束截取字符串。
字符串的替换方法:
- public String replace(char old,char new) 老字符替换成新字符
- public String replace(String old,String new) 老字符串替换成新字符串
字符串去除两端空格:
- public String trim()去除字符串两端的空格
对比字符串:
- public int compareTo(String str)通过字典顺序去比较,调用者减去传送者。若比不出来就通过长度比较。
转换:
- public byte[] getBytes(): 把字符串转换为字节数组。
- public char[] toCharArray(): 把字符串转换为字符数组。
- public static String valueOf(char[] chs): 把字符数组转成字符串。
- public static String valueOf(int i): 把int类型的数据转成字符串。
- 注意:String类的valueOf方法可以把任意类型的数据转成字符串。
- public String toLowerCase(): 把字符串转成小写。
- public String toUpperCase(): 把字符串转成大写。
- public String concat(String str): 把字符串拼接。