欢迎访问宙启技术站
智能推送

列举Java中常用的字符串处理函数及其使用方法

发布时间:2023-06-17 08:29:12

1. length():用于返回字符串的长度,如:String str = "hello"; int len = str.length(); // len = 5

2. charAt(int index):用于获取指定位置的字符,如:String str = "hello"; char c = str.charAt(1); // c = 'e'

3. substring(int beginIndex, int endIndex):用于截取指定范围的字符串,如:String str = "hello"; String subStr = str.substring(1, 4); // subStr = "ell"

4. indexOf(String str):用于获取指定子串在字符串中第一次出现的位置,如:String str = "hello"; int index = str.indexOf("l"); // index = 2

5. toLowerCase():用于将字符串中的字母全部转换为小写字母,如:String str = "HeLLo"; String newStr = str.toLowerCase(); // newStr = "hello"

6. toUpperCase():用于将字符串中的字母全部转换为大写字母,如:String str = "HeLLo"; String newStr = str.toUpperCase(); // newStr = "HELLO"

7. trim():用于去掉字符串两端的空格,如:String str = " hello "; String newStr = str.trim(); // newStr = "hello"

8. replace(char oldChar, char newChar):用于将字符串中的旧字符替换为新字符,如:String str = "hello"; String newStr = str.replace('l', 'L'); // newStr = "heLLo"

9. replaceAll(String regex, String replacement):用于将所有匹配正则表达式的子串都替换为新字符串,如:String str = "hello123world789"; String newStr = str.replaceAll("[0-9]+", ""); // newStr = "helloworld"

10. startsWith(String prefix):用于判断字符串是否以指定前缀开始,如:String str = "hello"; boolean b = str.startsWith("he"); // b = true

11. endsWith(String suffix):用于判断字符串是否以指定后缀结束,如:String str = "hello"; boolean b = str.endsWith("lo"); // b = true

12. isEmpty():用于判断字符串是否为空,如:String str = ""; boolean b = str.isEmpty(); // b = true

13. split(String regex):用于按照正则表达式切分字符串,返回切分后的字符串数组,如:String str = "hello,world"; String[] arr = str.split(","); // arr = {"hello","world"}

14. length():用于获取字符串数组的长度,如:String[] arr = {"hello","world"}; int len = arr.length; // len = 2

15. concat(String str):用于将指定字符串拼接到当前字符串的末尾,如:String str = "hello"; String newStr = str.concat(" world"); // newStr = "hello world"