一、String类的特点:
1,字符串对象一旦被初始化就不会被改变。
2,string类中的equals方法复写了Object中的equals方法,建立了string类自己的判断字符串对象是否相同的依据,其实就是比较字符串内容。
public class StringDemo {
public static void main(String[] args) {
stringDemo2();
}
public static void stringDemo2() {
String s = "abc";//创建一个字符串对象在常量池中。
String s1 = new String("abc");//创建两个对象一个new一个字符串对象在堆内存中。
System.out.println(s==s1);//false
System.out.println(s.equals(s1));
}
}
运行结果:
3,字符串常量池的特点:池中没有就建立,池中有,直接用。
public class StringDemo {
public static void main(String[] args) {
stringDemo1();
}
private static void stringDemo1() {
String s = "abc";//"abc"存储在字符串常量池中。
String s1 = "abc";
System.out.println(s==s1);//true?
}
}
运行结果:
3,将字节数组或者字符数组转成字符串可以通过String类的构造函数完成。
public class StringConstructorDemo {
public static void main(String[] args) {
stringConstructorDemo2();
}
private static void stringConstructorDemo2() {
char[] arr = {'w','a','p','q','x'};
String s = new String(arr,1,3);
System.out.println("s="+s);
}
}
运行结果:
二、字符串功能分类
1,获取
1.1 获取字符串中字符的个数(长度).
int length();
1.2 根据位置获取字符。
char charAt(int index);
1.3(1) 根据字符获取在字符串中的第一次出现的位置.
int indexOf(int ch)
int indexOf(int ch,int fromIndex):从指定位置进行ch的查找第一次出现位置
int indexOf(String str);
int indexOf(String str,int fromIndex);
1.3(2) 根据字符串获取在字符串中的第一次出现的位置.
int lastIndexOf(int ch)
int lastIndexOf(int ch,int fromIndex):从指定位置进行ch的查找第一次出现位置
int lastIndexOf(String str);
int lastIndexOf(String str,int fromIndex);
1.4 获取字符串中一部分字符串。也叫子串.
String substring(int beginIndex, int endIndex)//包含begin 不包含end 。
String substring(int beginIndex);
2,转换。
2.1 将字符串变成字符串数组(字符串的切割)
String[] split(String regex):涉及到正则表达式.
2.2 将字符串变成字符数组。
char[] toCharArray();
2.3 将字符串变成字节数组。
byte[] getBytes();
2.4 将字符串中的字母转成大小写。
String toUpperCase():大写
String toLowerCase():小写
2.5 将字符串中的内容进行替换
String replace(char oldch,char newch);
String replace(String s1,String s2);
2.6 将字符串两端的空格去除。
String trim();
2.7 将字符串进行连接 。
String concat(string);
3,判断
3.1 两个字符串内容是否相同啊
boolean equals(Object obj);
boolean equalsIgnoreCase(string str);忽略大写比较字符串内容。
3.2 字符串中是否包含指定字符串
boolean contains(string str);
3.3 字符串是否以指定字符串开头。是否以指定字符串结尾。
boolean startsWith(string);
boolean endsWith(string);
4,比较。
int compareTo() //按照字典顺序比较两个字符串大小
特点:如果按字典顺序此 String 对象位于参数字符串之前,则比较结果为一个负整数。如果按字典顺序此 String 对象位于参数字符串之后,则比较结果为一个正整数。如果这两个字符串相等,则结果为 0
5,去除字符串两端空格(常用)
trim();
6,对字符串池进行操作(实际开发不常用)
intern():对字符串池进行操作