中的String类提供了许多内置的函数(方法),用于操作字符串。以下是一些常用的String函数及其功能:
1. length():返回字符串的长度。
String str = "Hello";
int length = str.length(); // length will be 5
2. charAt(int index):返回指定索引位置的字符。
char ch = str.charAt(0); // ch will be 'H'
3. substring(int beginIndex):返回从指定索引开始到字符串末尾的子字符串。
String substr = str.substring(2); // substr will be "llo"
4. substring(int beginIndex, int endIndex):返回从beginIndex到endIndex之间的子字符串,不包括endIndex位置的字符。
String substr = str.substring(1, 4); // substr will be "ell"
5. toUpperCase() 和 toLowerCase():将字符串转换为大写或小写。
String upper = str.toUpperCase(); // upper will be "HELLO"
String lower = str.toLowerCase(); // lower will be "hello"
6. indexOf(String str) 和 lastIndexOf(String str):返回指定子字符串在当前字符串中第一次和最后一次出现的索引位置。
int firstIndex = str.indexOf("l"); // firstIndex will be 2
int lastIndex = str.lastIndexOf("l"); // lastIndex will be 3
7. replace(char oldChar, char newChar) 和 replace(CharSequence target, CharSequence replacement):替换字符串中的字符或子字符串。
String replaced = str.replace('l', 'p'); // replaced will be "Heppo"
String replaced2 = str.replace("lo", "xy"); // replaced2 will be "Helxy"
8. startsWith(String prefix) 和 endsWith(String suffix):检查字符串是否以指定的前缀或后缀开头或结尾。
boolean starts = str.startsWith("He"); // starts will be true
boolean ends = str.endsWith("lo"); // ends will be true
这些是中String类的一些常用函数,能够帮助进行字符串的处理、操作和查询。