这里介绍一些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.java.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.java.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.java.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.java.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); } } |