String类常用的操作:
一、获取
1、字符串中包含的字符数,也就是字符串的长度。
int length();
数组里面的长度length是属性,字符串的长度length()是方法。
2、根据位置获取位置上某个字符。
char charAt(int index);
3、根据字符获取字符在字符串中的位置。
int indexOf(int ch);
int indexOf(int ch, int fromIndex);
int indexOf(String str);
int indexOf(String str,int fromIndex);
int lastIndexOf(int ch);
二、判断
1、字符串中是否包含某一个子串。
boolean contains(str);
2、字符串是否为空
boolean isEmpty();原理是判断长度是否为0
3、字符串是否以指定内容开头。
boolean startsWith(str);
4、字符串是否以指定内容结尾。
boolean endsWith(str);
5、判断字符串内容是否相同。
boolean equals(str);
6、判断内容是否相同,并忽略大小写。
boolean equalsIgnoreCase();
三、转换
1、将字符数组转换成字符串。
构造函数:String (char[]) / String (char[],offset,count)
静态方法:static String valueOf(char[ ])
2、将字符串转换成字符数组
char[ ] toCharArray()
3、将基本数据类型转换成字符串
static String valueOf()
四、替换
String replace (oldchar,newchar)
五、切割
String[ ] split(regex)
六、子串,获取字符串中的一部分。
String substring(begin)
String substring(begin,end)
七、转换大小写,去除空格,比较
1、大小写转换
String toUpperCase();
String toLowerCase();
2、将字符串两端的多个空格去除
String trim();
3、对两个字符串进行自然顺序的比较
int compareTo(String);