String類是我們最常使用的類。字符串類的方法我們必須非常熟悉!我們列出常用的方法,請大家熟悉。
表5-2 String類的常用方法列表
【示例】String類常用方法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
StringTest1 {
public
static
void
main(String[] args) {
String s1 =
"core Java"
;
String s2 =
"Core Java"
;
System.out.println(s1.charAt(
3
));
//提取下標為3的字符
System.out.println(s2.length());
//字符串的長度
System.out.println(s1.equals(s2));
//比較兩個字符串是否相等
System.out.println(s1.equalsIgnoreCase(s2));
//比較兩個字符串(忽略大小寫)
System.out.println(s1.indexOf(
"Java"
));
//字符串s1中是否包含Java
System.out.println(s1.indexOf(
"apple"
));
//字符串s1中是否包含apple
String s = s1.replace(
' '
,
'&'
);
//將s1中的空格替換成&
System.out.println(
"result is :"
+ s);
}
}
|
【示例】String類常用方法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public
class
StringTest2 {
public
static
void
main(String[] args) {
String s =
""
;
String s1 =
"How are you?"
;
System.out.println(s1.startsWith(
"How"
));
//是否以How開頭
System.out.println(s1.endsWith(
"you"
));
//是否以you結尾
s = s1.substring(
4
);
//提取子字符串:從下標為4的開始到字符串結尾為止
System.out.println(s);
s = s1.substring(
4
,
7
);
//提取子字符串:下標[4, 7) 不包括7
System.out.println(s);
s = s1.toLowerCase();
//轉小寫
System.out.println(s);
s = s1.toUpperCase();
//轉大寫
System.out.println(s);
String s2 =
" How old are you!! "
;
s = s2.trim();
//去除字符串首尾的空格。注意:中間的空格不能去除
System.out.println(s);
System.out.println(s2);
//因為String是不可變字符串,所以s2不變
}
}
|