java學(xué)習(xí)之字符串
- 字符串的比較
public class Stringdome {
public static void main(String[] args) {
String str ="hello";
String str1= new String ("hello");
System.out.println(str==st1);
}
}
public class Stringdome {
public static void main(String[] args) {
String str ="hello";
String str1= new String ("hello");
System.out.println(str.equals(str1));
}
}
這是字符串通過==
和str.equals
比較字符串是否相同
兩者的不同點(diǎn)在于前者是比較字符串的地址,而后者是比較字符串的內(nèi)容
所以前者輸出的是false
后者輸出的是true
好習(xí)慣
開發(fā)中盡量用String str="hello";
這類直接賦值的語句箱锐,不要用String str1=new String("hello");
這類重新開辟空間的賦值語句
- 字符串內(nèi)容不可更改
public static void main(String[] args) {
String str ="hello";
str=str+"World";
System.out.println(str);
}
雖然輸出的結(jié)果是helloWorld
但是內(nèi)存地址已經(jīng)改變了
-
字符串常用的方法
- 字符串長度:
length()
- 字符串轉(zhuǎn)換數(shù)組:
toCharArray()
- 從字符串中取出指定位置的字符:
charAt()
- 字符串與byte數(shù)組的轉(zhuǎn)換:
getByte()
- 過濾字符串中存在的字符:
indeOf()
可用于尋找特殊字符例如:@
敏感文字
等等 - 去掉字符串的前后空格:
trim()
- 從字符串中取出子字符串:
subString()
- 大小寫轉(zhuǎn)換:
toLowerCase() toUpperCase()
- 字符串長度:
StringBuffer的使用
認(rèn)識(shí)StringBuffer
本身也是操作字符串比勉,但是和String不同,StringBuffer是可更改的驹止,且不需開辟新的內(nèi)存空間浩聋,作為一個(gè)操作類,必須要通過實(shí)例化操作
public class Stringdome {
public static void main(String[] args) {
StringBuffer sb =new StringBuffer();
sb.append("i love ");
System.out.println(sb.toString());
tell(sb);
System.out.println(sb.toString());
}
public static void tell(StringBuffer s)
{
s.append("jikexueyuan");
}
}
StringBuffer的常用方法
- 尾部追加:
append()
- 插入:
insert()
- 代替:
replace()
- 索引子字符串的第一個(gè)字符:
indexOf()
- StringBuilder的使用