Day18:字符串相关类
String类:构造字符串对象
—— 常用对象:字符串常量对象时双引号括起的字符序列。
—— 字符串的字符使用Unicode字符编码,一个字符占两个字节。
——String:代表不可变的字符序列。底层用char[]存放。
——String是final的。
常用方法:
1.public int lenth()
2.public char charAt(int index):返回在指定index位置的字符。index从0开始。
3.public boolean equals(Object anObject):比较两个字符串是否相等。相等为true,否则返回false。
4.public int compareTo(String anotherString):
5.public int indexOf(String s):返回s字符串在当前字符串中首次出现的位置。若没有,返回-1。
6.public int indexOf(String s, int start startpoint):返回s字符串最后一次在当前字符串中出现的位置。若无,返回-1
7.public int lastIndexOf(String s):返回字符串最后一次在当前字符串中出现的位置。若无,返回-1.
8.public int lastIndexOf(String s, int startpoint):
9.public boolean startWith(String prefix):判断当前字符串是否以prefix开始。
10.public boolean endsWith(String suffix):当前字符串是否以prefix结束。
11.public boolean regionMatches(int firstStart , String other , int otherStart):判断当前字符串从firstStart开始开始的 子串从另一个字符串other从otherStart开始,lenth长度的字符串。
12.public String substring(int startpoint):返回从start开始到结束的字符串。
13.public String substring(int start , int end):返回从start开始到end结束的一个左闭右开的字符串。
14.public String replace(char oldChar,char newChar):替换。
15.public String replaceAll(String old,String new)
16.public String trim():去除当前字符串中首尾出现的空格,若有多个,就去除多个。
17.public String concat(String str):连接当前字符串与str
18.public String[] split(String regex)按照regex将当前字符串分割,拆分成多个字符串,整体返回String[]。
1.字符串与基本数据类型、包装类之间转换
①字符串---->基本数据类型、包装类:调用相应的包装类的parseXxx(String str);
②基本数据类型---->字符串:调用字符串重载的valueOf()方法。
2.字符串与字节数组之间的转换
①字符串--->字节数组:调用字符串的getBytes()。
②字节数组--->字符串:调用字符串的构造器。
3.字符串与字符数组间的转换
①字符串--->字符数组:调用字符串的toCharArray();
②字符数组--->字符串:调用字符串的构造器。
StringBuffer:
代表可变的字符序列,可以对字符串内容进行增删。
方法:
1.append():添加。
2.insert(int index,String str):指定位置插入一个字符串。
3.reverse():反转此StringBuffer。
4.delete(int startIndex,int endIndex):删除指定位置字符。
5.setCharAt(int index,char ch):修改指定位置的字符。
6.length():长度。
StringBuilder:
可变的字符序列,jdk5.0新加入的,线程不安全,效率高于StringBuffer。
效率:StringBuilder > StringBuffer > String.