Java中的String函数有哪些常用的操作?
Java中的String是一个不可变的字符序列,使用String类可以封装一些字符串相关的操作方法,以下是一些常用的String函数:
1. length():获取字符串的长度。例如:"Hello".length()返回值为5。
2. charAt(int index):获取指定索引位置上的字符。例如:"Hello".charAt(1)返回值为'e'。
3. indexOf(String str):获取指定字符串在当前字符串中第一次出现的位置。例如:"Hello world".indexOf("l")返回值为2。
4. substring(int beginIndex, int endIndex):获取从指定索引位置开始到指定位置结束的子字符串。例如:"Hello world".substring(3,7)返回值为"lo w"。
5. equals(String str):判断当前字符串是否与指定字符串相等。例如:"Hello world".equals("Hello")返回值为false。
6. equalsIgnoreCase(String str):忽略大小写判断当前字符串是否与指定字符串相等。例如:"Hello World".equalsIgnoreCase("hello world")返回值为true。
7. toLowerCase():将字符串转化为小写字母。例如:"Hello World".toLowerCase()返回值为"hello world"。
8. toUpperCase():将字符串转化为大写字母。例如:"Hello World".toUpperCase()返回值为"HELLO WORLD"。
9. trim():去除字符串首尾的空格。例如:" Hello World ".trim()返回值为"Hello World"。
10. replace(char oldChar, char newChar):用指定字符替换当前字符串中的指定字符。例如:"Hello World".replace('o','@')返回值为"Hell@ W@rld"。
11. replaceAll(String regex, String replacement):将当前字符串中所匹配的符合正则表达式所代表的替换为指定字符串。例如:"Hello World".replaceAll("Worl","Final")返回值为"Hello Finald"。
12. startsWith(String prefix):判断当前字符串是否以指定字符串开头。例如:"Hello World".startsWith("Hel")返回值为true。
13. endsWith(String suffix):判断当前字符串是否以指定字符串结尾。例如:"Hello World".endsWith("rld")返回值为true。
14. split(String regex):将当前字符串按照指定的正则表达式分割为字符串数组。例如:"Hello World".split(" ")返回值为["Hello","World"]。
15. format(String format, Object... args):用指定的格式化字符串格式化当前字符串。例如:String str=String.format("%s is %d years old","Tom",20),返回值为"Tom is 20 years old"。
总之,Java中的String函数非常的丰富和实用,可以通过这些函数来实现字符串的各种操作。
