Java面向对象-String类(下)
String类常用方法及基本使用
我们首先来学习基本使用Jdk api chm文档:
我们这里推荐使用1.6 是中文的。下载地址:http://www.java1234.com/a/javaziliao/shuji/2013/0506/355.html
我们双击打开:
我们点击 左上角 显示:
输入String 搜索 然后我们会在右侧找到String类的描述,可以查到String类的所有信息 包括描述 方法 属性;
这里介绍一些String类的常用方法:
1, char chartAt(int index) 返回指定索引处的char值
这里的index 是从0开始的;
我们先上下实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package
com.java1234.chap03.sec08;
public
class
Demo5 {
public
static
void
main(String[] args) {
String name=
"张三"
;
char
ming=name.charAt(
1
);
System.out.println(ming);
String str=
"我是中国人"
;
for
(
int
i=
0
;i<str.length();i++){
System.out.println(str.charAt(i));
}
}
}
|
运行输出:
三
我
是
中
国
人
2,int length() 返回字符串的长度;
在前面一个例子里我们已经演示了;
3,int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
1
2
3
4
5
6
7
8
9
10
11
|
package
com.java1234.chap03.sec08;
public
class
Demo06 {
public
static
void
main(String[] args) {
// indexOf方法使用实例
String str=
"abcdefghijdklmoqprstuds"
;
System.out.println(
"d在字符串str中第一次出现的索引位置:"
+str.indexOf(
'd'
));
System.out.println(
"d在字符串str中第一次出现的索引位置,从索引4位置开始:"
+str.indexOf(
'd'
,
4
));
}
}
|
4,String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package
com.java1234.chap03.sec08;
public
class
Demo07 {
public
static
void
main(String[] args) {
// substring方式读取
String str=
"不开心每一天"
;
String str2=
"不开心每一天,不可能"
;
String newStr=str.substring(
1
);
System.out.println(newStr);
String newStr2=str2.substring(
1
,
6
);
System.out.println(newStr2);
}
}
|
5,public String toUpperCase() String 中的所有字符都转换为大写
1
2
3
4
5
6
7
8
9
10
11
12
|
package
com.java1234.chap03.sec08;
public
class
Demo08 {
public
static
void
main(String[] args) {
String str=
"I'm a boy!"
;
String upStr=str.toUpperCase();
// 转成大写
System.out.println(upStr);
String lowerStr=upStr.toLowerCase();
// 转成小写
System.out.println(lowerStr);
}
}
|