因為常用方法較多,所以分為3篇
1.length() : 回傳字串長度,此處的length有別于陣列中的length陣列中的length為屬性,此處的length為方法,
2.charAt() :將String型別變數視作一個字符陣列,傳入合法下標([ 0 , str.length() ) ),回傳該下標位置字符,
3.toCharArray() :將String型別變數拆解為一個字符型別陣列,
下面通過代碼理解以上三種方法:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str = "為中華之崛起而讀書";
System.out.println(str.length());
System.out.println(str.charAt(0) == '為');
System.out.println(str.charAt(0));
char[] chars = str.toCharArray();
System.out.println(Arrays.toString(chars));
}
}
運行結果:

這三種方法常用于字串的遍歷:
public class Main {
public static void main(String[] args) {
String str = "為中華之崛起而讀書";
//方法一
int length = str.length();
for(int i = 0; i < length; i++){
System.out.print(str.charAt(i) + " ");
}
System.out.println();
for(int i = 0; i < str.length(); i++){
System.out.print(str.charAt(i)+ " ");
}
System.out.println();
//方法二
char[] charStr = str.toCharArray();
for(int i = 0; i < charStr.length; i++){
System.out.print(charStr[i]+ " ");
}
System.out.println();
//方法三
for(char ch : str.toCharArray()){
System.out.print(ch+ " ");
}
System.out.println();
}
}
運行結果:

4.indexOf() / lastIndexOf() :該方法存在多種多載

第一種是傳入一個字符,回傳該字符在字串中第一次出現的位置,如不存在回傳-1;
第二種是傳入一個字串,若母字串中存在傳入的字串,回傳傳入字串第一個字符在母字串中第一次出現的位置,若不存在,回傳-1;
第三種是第一種加了起始搜索位置;
第四種是第二種加了起始搜索位置;
lastIndexOf() 和 indexOf() 不同是,indexOf() 是從字串的開始往后找,lastIndexOf() 是從字串的結尾往開始方向找,所以在不對lastIndexOf() 用法進行重復介紹
通過代碼理解indexOf() :
public static void main(String[] args) {
String str = "我是中國人,我愛中國,我愛我的家鄉";
System.out.println("\'我\' 在str中第一次出現的位置是:" + str.indexOf('我'));
System.out.println("\"我愛中國\" 在str中第一次出現的位置是:" + str.indexOf("我愛"));
System.out.println("從位置3開始 \'我\' 第一次出現的位置是:" + str.indexOf('我',3));
System.out.println("從位置3開始 \"我愛\" 第一次出現的位置是:" + str.indexOf("我愛",7));
}
運行結果:

indexOf() 可以用于查找一個字符/字串 在字串中出現的次數:
public static void main(String[] args) {
String str = "我是中國人,我愛我的,我愛我的家鄉,我愛我的學校,我愛我的家";
//用來存放要查的字串
String t = "我愛";
//用于存放每次回圈時 indexOf() 中的開始查找位置
int index = str.indexOf(t,0);
//用于計數
int count = 0;
while (index != -1) {
count++;
System.out.println("\"" + t + "\"在str中第" + count + "出現的位置是" + index);
//這里index存放了str中 下一個 t 的位置,若沒有下一個,則為-1
index = str.indexOf(t, index + t.length());
} ;
System.out.println("\"" + t + "\"在str中一共出現的次數是" + count);
}
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/261716.html
標籤:java
上一篇:連續兩次遞回程序詳解
