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

Java中的字符串处理函数:常见的字符串处理函数以及使用技巧

发布时间:2023-06-29 23:14:17

Java中提供了许多用于处理字符串的函数,这些函数可以使开发人员更轻松地对字符串进行操作和处理。下面列举了一些常见的字符串处理函数及其使用技巧。

1. length(): 获取字符串的长度

String str = "Hello World";

int length = str.length(); 

// length的值为11

2. charAt(int index): 获取指定索引位置的字符

char ch = str.charAt(0);

// ch的值为'H'

3. substring(int beginIndex): 截取指定位置到字符串末尾的子串

String subStr = str.substring(6);

// subStr的值为"World"

4. substring(int beginIndex, int endIndex): 截取指定开始和结束位置之间的子串

String subStr = str.substring(0, 5);

// subStr的值为"Hello"

5. concat(String str): 字符串拼接

String concatStr = str.concat("Java");

// concatStr的值为"Hello World Java"

6. indexOf(String str): 返回字符串中 次出现的指定子字符串的位置

int index = str.indexOf("World");

// index的值为6

7. lastIndexOf(String str): 返回字符串中最后一次出现的指定子字符串的位置

int lastIndex = str.lastIndexOf("o");

// lastIndex的值为7

8. replace(char oldChar, char newChar): 替换字符串中所有的旧字符为新字符

String newStr = str.replace('o', 'a');

// newStr的值为"Hella Warld"

9. toLowerCase(): 将字符串中的所有字符转换为小写

String lowerStr = str.toLowerCase();

// lowerStr的值为"hello world"

10. toUpperCase(): 将字符串中的所有字符转换为大写

String upperStr = str.toUpperCase();

// upperStr的值为"HELLO WORLD"

11. trim(): 去除字符串前后的空格

String spaceStr = "  Hello World  ";

String trimStr = spaceStr.trim();

// trimStr的值为"Hello World"

12. split(String regex): 根据正则表达式将字符串切割成字符串数组

String[] parts = str.split(" ");

// parts为["Hello", "World"]

13. startsWith(String prefix): 判断字符串是否以指定前缀开头

boolean startsWithHello = str.startsWith("Hello");

// startsWithHello的值为true

14. endsWith(String suffix): 判断字符串是否以指定后缀结尾

boolean endsWithWorld = str.endsWith("World");

// endsWithWorld的值为true

15. equals(Object obj): 判断字符串是否与给定对象(String)相等

boolean isEqual = str.equals("Hello World");

// isEqual的值为true

16. equalsIgnoreCase(String anotherString): 忽略大小写判断字符串是否相等

boolean isCaseEqual = str.equalsIgnoreCase("hello world");

// isCaseEqual的值为true

这些函数只是Java字符串处理函数中的一部分,有助于开发人员更方便地对字符串进行处理。