字符串
- Java中,和字符串有关的类有:String、StringBuffer、StringBuilder;所有的字符串操作都是由上述的3个类管理。
- 下文,将介绍String字符串类的基本原理。
String初始化
String的初始化,就是指String类的构造方法,以下是String类的构造方法(具体的详见API文档,只因API文档看着蛋疼,先抽取这几个出来看看):
初始化方式:
String()
--------- 初始化一个String对象,表示一个空字符序列String(String value)
--------- 利用一个直接量创建一个新串String(char[] value)
--------- 利用一个字符数组创建String(char[] value,int offset,int count)
--------- 截取字符数组,从offset开始count个字符创建String(StringBuffer buffer)
--------- 利用StringBuffer创建
public class StringDemo {
public static void main(String[] args) {
//方式1
//String(String original):把字符串数据封装成字符串对象
String s1 = new String("hello");
System.out.println("s1:"+s1);
System.out.println("---------");
//方式2
//String(char[] value):把字符数组的数据封装成字符串对象
char[] chs = {'h','e','l','l','o'};
String s2 = new String(chs);
System.out.println("s2:"+s2);
System.out.println("---------");
//方式3
//String(char[] value, int index, int count):把字符数组中的一部分数据封装成字符串对象
//String s3 = new String(chs,0,chs.length);
String s3 = new String(chs,1,3);
System.out.println("s3:"+s3);
System.out.println("---------");
//方式4
String s4 = "hello";
System.out.println("s4:"+s4);
}
}
String的两种初始化方式比较
String str=“hello”;
这种方式创建字符串的时候:
- JVM先检查字符串常量池中是否存在
- 存在,返回该串在字符串常量池中的内存地址
- 不存在,在常量池中创建该串的并返回地址;
String str=new String(“hello”);
这种方式创建字符串的时候:
- JVM先检查字符串常量池中是否存在
- 存在,返回该串在池中的地址
- 不存在,在池中创建,复制该串到堆内存中新创建的对象中,返回堆中的地址;
- 创建了两个对象,一个对象位于字符串常量池中,一个对象是位于堆内存中;
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
String str4 = new String("hello");
System.out.println("str1==str2?" + (str1 == str2)); //true
System.out.println("str3==str4?" + (str3 == str4)); //false
System.out.println("str3==str4?" + (str3 == str4)); //false
System.out.println("str3.equals(str2)?" + (str3.equals(str4))); //true
原理解析:
注:上图来自“黑马程序员”的上课笔记。
String类方法
最常用
求字符串长度
public int length()
该方法用于获取字符串的长度
String str = new String("asdfzxc");
int strlength = str.length();//strlength = 7
求字符串某一位置字符
public char charAt(int index)
//返回字符串中指定位置的字符;注意字符串中第一个字符索引是0,最后一个是length()-1。
String str = new String("asdfzxc");
char ch = str.charAt(4);//ch = z
字符串转换
1)public String toLowerCase()
//返回将当前字符串中所有字符转换成小写后的新串
2)public String toUpperCase()
//返回将当前字符串中所有字符转换成大写后的新串
3)public char[] toCharArray()
//把字符串转换为字符数组
判断操作
String类的判断功能:
-
boolean equals(Object obj)
:比较字符串的内容是否相同。如果一个方法的形式参数是Object,那么这里我们就可以传递它的任意的子类对象。 -
boolean equalsIgnoreCase(String str)
:比较字符串的内容是否相同, 忽略大小写 -
boolean startsWith(String str)
:判断字符串对象是否以指定的str开头 -
boolean endsWith(String str)
:判断字符串对象是否以指定的str结尾 -
boolean contains(String str)
:判断该字符串中 是否包含给定的字符串 -
boolean isEmpty()
:判断该字符串的内容是否为空的字符串
比较操作
String类的比较概要:
-
public int compareTo(String anotherString)
//首先,会对两个字符串左对齐,然后从左到右一次比较;如果相同,继续;如果不同,则计算不同的两个字符的ASCII值的差,返回就行了。与后面的其他字符没关系。 -
public int compareToIgnore(String anotherString)
//与compareTo方法相似,但忽略大小写。 -
public boolean equals(Object anotherObject)
//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。 -
public boolean equalsIgnoreCase(String anotherString)
//与equals方法相似,但忽略大小写。
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true
}
查找操作
String类查找操作方法概览:
-
public int indexOf(int ch/String str)
//用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。 -
public int indexOf(int ch/String str, int fromIndex)
//改方法与第一种类似,区别在于该方法从fromIndex位置向后查找。 -
public int lastIndexOf(int ch/String str)
//该方法与第一种类似,区别在于该方法从字符串的末尾位置向前查找。 -
public int lastIndexOf(int ch/String str, int fromIndex)
//该方法与第二种方法类似,区别于该方法从fromIndex位置向前查找。
public static void main(String[] args) {
String str = "I am a good student";
int a = str.indexOf('a');//a = 2
int b = str.indexOf("good");//b = 7
int c = str.indexOf("w",2);//c = -1
int d = str.lastIndexOf("a");//d = 5
int e = str.lastIndexOf("a",3);//e = 2
}
替换操作
String类的替换操作概览:
-
public String replace(char oldChar, char newChar)
//用字符newChar替换当前字符串中所有的oldChar字符,并返回一个新的字符串。 -
public String replaceFirst(String regex, String replacement)
//该方法用字符replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,应将新的字符串返回。 -
public String replaceAll(String regex, String replacement)
//该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,应将新的字符串返回。
String str = "asdzxcasd";
String str1 = str.replace('a','g');//str1 = "gsdzxcgsd"
String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh"
String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd"
String str4 = str.replaceAll("asd","fgh");//str4 = "fghzxcfgh"
子串相关
-
public String substring(int beginIndex)
//该方法从beginIndex位置起、到本串结束,作为一个新的字符串返回。 -
public String substring(int beginIndex, int endIndex)
//该方法从beginIndex位置起、到endIndex-1位置的字符,作为一个新的字符串返回。 -
public CharSequence subSequence(int beginIndex, int endIndex)
- 其实subSequence()内部就是调用的substring(beginIndex, endIndex),只是返回值不同。
- subString返回的是String,subSequence返回的是实现了CharSequence接口的类,也就是说使用subSequence得到的结果,只能使用CharSequence接口中的方法。
String str1 = new String("asdfzxc");
String str2 = str1.substring(2);//str2 = "dfzxc"
String str3 = str1.substring(2,5);//str3 = "dfz"
MISC
String trim()
截去字符串两端的空格,但对于中间的空格不处理。
regionMatches(boolean b, int firstStart, String other, int otherStart, int length)
从当前字符串的firstStart位置开始比较,取长度为length的一个子字符串,other字符串从otherStart位置开始,指定另外一个长度为length的字符串,两字符串比较,当b为true时字符串不区分大小写。
String[] split(String str)
将str作为分隔符进行字符串分解,分解后的字字符串在字符串数组中返回。
public class StringDemo {
public static void main(String[] args) {
//创建字符串对象
String s1 = "helloworld";
String s2 = " helloworld ";
String s3 = " hello world ";
System.out.println("---"+s1+"---");
System.out.println("---"+s1.trim()+"---");
System.out.println("---"+s2+"---");
System.out.println("---"+s2.trim()+"---"); //去两端的空格
System.out.println("---"+s3+"---");
System.out.println("---"+s3.trim()+"---"); //去两端不去中间的空格
System.out.println("-------------------");
//String[] split(String str); 依据参数来分割字符串
//创建字符串对象
String s4 = "aa,bb,cc";
String[] strArray = s4.split(",");
for(int x=0; x<strArray.length; x++) {
System.out.println(strArray[x]);
}
}
}
String类的串转换
String串转换为基本类型
Notice:
- 所转换的串必须由0~9之间的字符组成,不能含有其他字符;
- 所转换的串的大小必须在基本数据类型可容纳的范围之内;
- java.lang包中有Byte、Short、Integer、Float、Double类的调用方法:
1) public static byte parseByte(String s) //把串转换为一个byte类型
2) public static short parseShort(String s) //把串转换为一个short类型
3) public static short parseInt(String s) //把串转换为一个short类型
4) public static long parseLong(String s) //把串转换为一个long类型
5) public static float parseFloat(String s) //把串转换为一个float类型
6) public static double parseDouble(String s) //把串转换为一个double类型
//试一试:
public static void main(String[] args) {
String str = new String("-127");
byte bb = Byte.parseByte(str); //str的范围为:[-127, 127], 超出则报错
System.out.println(bb); //输出:-127
String str1 = new String("32767");
short ss = Short.parseShort(str1); //str1的范围[-32767, 32767], 超出则报错
System.out.println(ss);
}
基本类型串转换为String串
String类中提供了String valueOf()放法,用作基本类型转换为字符串类型。
1)static String valueOf(char data[])
2)static String valueOf(char data[], int offset, int count)
3)static String valueOf(boolean b)
4)static String valueOf(char c)
5)static String valueOf(int i)
6)static String valueOf(long l)
7)static String valueOf(float f)
8)static String valueOf(double d)
public class Main {
public static void main(String[] args) {
byte a = 10;
String str_a = String.valueOf(a);
System.out.println(getType(a)); //class java.lang.Byte
System.out.println(getType(str_a)); //class java.lang.String
}
public static String getType(Object o){ //获取变量类型方法
return o.getClass().toString(); //使用int类型的getClass()方法
}
}
规避字符串的空指针异常
//避免空指针异常
//防止String类的空指针异常,以下的代码不安全,加入在调用这个方法时传入的参数是个空指针,则会发生空指针异常
public static void test01(String str) {
if(str.equals("china")) { //str.equals("china")的调用者是str,str可能发生为空的情况
System.out.println("right");
}
else {
System.out.println("error");
}
}
//解决方案:让常用作方法的调用者,可以避免空指针异常
public static void test02(String str) {
if("china".equals(str)) {
System.out.println("right");
}
else {
System.out.println("error");
}
}