一、比较
基本数据的比较可以使用“==”,但是在对象中使用“==”比较,因为对象中存放的是地址值,因此是进行地址的比较。如果要对对象的内容给进行比较,可以使用如下方法:
1、public boolean equals(object obj),参数可以是任何对象,只有参数是一个字符串并且内容相同的才会返回true,否则返回false.
2、public boolean equalsIgnoreCase(String str),忽略大小写进行比较
注意事项:
1、任何兑现个都能用object进行接收
2、equals方法具有对称性,a.equals(b)和b.equals(b)结果是一样的。
3、如果比较双方一个是常量,一个是变量,建议吧常量字符放在前面,目的是防止变量如果为null,编译器会报错。
4、只用用“”生成的字符串才会放到字符常量池中。
推荐使用:"abc".equals(str1) 不推荐使用:str1.equals("abc")
public class Demo02Equal {
public static void main(String[] args) {
String str1 = "abc";//只用用“”生成的字符串才会放到字符常量池中
String str2 = "abc";
char[] charArray = {'a','b','c'};//不会放到常量池中
String str3 = new String(charArray);
System.out.println("str1字符串内容:" + str1);
System.out.println("str2字符串内容:" + str2);
System.out.println("str3字符串内容:" + str3);
System.out.println("=============“==比较”============");
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str3);
System.out.println("===========“equals比较”==========");
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str2.equals(str3));
System.out.println("abc".equals(str1));
}
}
输出结果:
str1字符串内容:abc
str2字符串内容:abc
str3字符串内容:abc
=============“==比较”============
true
false
false
===========“equals比较”==========
true
true
true
true
二、查找
public int length() :获取当前字符串长度
public char charAt(int index):查找指定索引位置的字符
public int indexOf(String str):查找str字符第一次出现的位置,如果查找不到返回-1
public class Demo03Check {
public static void main(String[] args) {
String str = "HelloWorld";
System.out.println("字符串长度:" + str.length());
//查找指定位置字符
System.out.println("第四个字符是"+str.charAt(4));
//查找特定字符第一次出现的位置
System.out.println("llo第一次出现在位置:" + str.indexOf("llo") );
System.out.println("abc第一次出现在位置:" + str.indexOf("abc") );
}
}
输出结果:
字符串长度:10
第四个字符是o
llo第一次出现在位置:2
abc第一次出现在位置:-1
三、合并和截取
public String concat(String str):将当前字符串和字符串str合并,将合并后的新字符串作为结果返回。
public String substring(int index):截取从索引开始到结束的所有字符串,并作为结果返回。
public String substring(int begin,int end):截取从begin到end之间的字符串,并作为结果返回。
备注:[begin,end),包含左边,不包含右边
public char[] toCharArray(),将当前字符串拆分成一个个字符,并将这些字符作为字符数组返回。
public byte[] toBytes(),将当前字符串拆解成字符对应的字节,并作为结果返回。
public String replace(CharSequence oldString, CharSequence newString) 将所有出现的老字符串替换成新字符串,并将替换后的结果作为返回值。
备注:CharSequence可以认为就是String
public String[] split(String regex):按照参数的规则,将字符串拆分成若干份,并将拆分后的字符串数组作为结果返回。注意:regex是正则表达式,因此如果使用"."这个符号作为拆分一句,需要写成“\\.”