c++ string類的常用方法_Java中String類的幾種常用方法介紹1. length()2. substring(int beginIndex, int endIndex)3. charAt(int index):char4. indexOf(String str)5. isEmpty()6. replaceAll(String regex, String replacement)
c++ string類的常用方法_Java中String類的幾種常用方法介紹1. length()2. substring(int beginIndex, int endIndex)3. charAt(int index):char4. indexOf(String str)5. isEmpty()6. replaceAll(String regex, String replacement)
1. length()
傳回值:int
說明:傳回指定字元串的長度
public static void main(String[] args) {String str = "This is a computer.";// 傳回指定字元串的長度int length = str.length();System.out.println(length); // 19}
2. substring(int beginIndex, int endIndex)
入參:beginIndex是開始索引的位置,endIndex結束索引的位置
傳回值:String
說明:截取字元串,索引是從0開始,截取的字元串隻截取到結束索引之前,以下程式中,beginIndex是2,對應i,endIndex是11,對應o,截取之後不是"is is a co",而是"is is a c",是以,使用這個方法時,要注意endIndex指向的位置
public static void main(String[] args) {String str = "This is a computer.";// 截取字元串String newStr = str.substring(2, 11);System.out.println(newStr); // is is a c }
3. charAt(int index):char
入參:int
傳回值:char
功能:指定索引,傳回索引處的字元
public static void main(String[] args) {String str = "This is a dog.";// 傳回指定索引處的charchar ch = str.charAt(3);System.out.println(ch); // s}
4. indexOf(String str)
入參:String
傳回值:int
說明:傳回指定字元在該字元串中第一次出現的索引,在"This is a computer."中,有兩個"is",indexOf(String str)方法可以擷取某個字元串第一出現的位置
public static void main(String[] args) {String str = "This is a computer.";// 傳回指定字元在該字元串中第一次出現的索引int index = str.indexOf("is");System.out.println(index); // 2}