Java面向物件-- String 類 常用方法及基本使用
阿新 • • 發佈:2018-11-08
首先來學習基本使用Jdk api chm文件:
點選 左上角-顯示:
1, char chartAt(int index) 返回指定索引處的char值
這裡的index 是從0開始的;
package com.xuyigang1234.chp02.string; public class Demo01 { public static void main(String[] args) { String name="小白"; char name1=name.charAt(1); System.out.println("name1為:"+name1); String aa="我愛學習"; for(int i=0;i<aa.length();i++) { System.out.println(aa.charAt(i)+" "); } } }
2,int length() 返回字串的長度;
3,int indexOf(int ch) 返回指定字元在此字串中第一次出現處的索引。
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) 返回一個新的字串,它是此字串的一個子字串。
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 中的所有字元都轉換為大寫
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); } }