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

Java中的字符串处理函数你必须知道

发布时间:2023-05-31 02:23:15

在Java中,字符串处理是基本操作之一,因此掌握字符串处理函数非常重要,可以大幅提高编程效率,以下是必须知道的Java中字符串处理函数。

1. length():返回字符串的长度。

例如:String s = "hello"; int len = s.length(); // len will be 5

2. charAt(index):返回字符串中指定位置的字符。

例如:String s = "hello"; char c = s.charAt(1); // c will be 'e'

3. substring(int beginIndex, int endIndex):返回字符串中从指定位置到结束位置的子字符串。

例如:String s = "hello"; String sub = s.substring(1, 4); // sub will be "ell"

4. contains(CharSequence s):判断字符串中是否包含指定的子字符串。

例如:String s = "hello"; boolean isContains = s.contains("ell"); // isContains will be true

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

例如:String s = "hello"; int index = s.indexOf("l"); // index will be 2

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

例如:String s = "hello"; int index = s.lastIndexOf("l"); // index will be 3

7. replace(char oldChar, char newChar):替换字符串中的字符。

例如:String s = "hello"; String str = s.replace('l', 'x'); // str will be "hexxo"

8. toUpperCase():将字符串转换为大写字母。

例如:String s = "hello"; String str = s.toUpperCase(); // str will be "HELLO"

9. toLowerCase():将字符串转换为小写字母。

例如:String s = "HELLO"; String str = s.toLowerCase(); // str will be "hello"

10. trim():去除字符串两端的空格。

例如:String s = "   hello   "; String str = s.trim(); // str will be "hello"

11. split(String regex):根据给定正则表达式分隔字符串。

例如:String s = "hello,world"; String[] strArr = s.split(","); // strArr will be ["hello", "world"]

12. substring(int beginIndex):返回字符串中从指定位置开始的子字符串。

例如:String s = "hello"; String sub = s.substring(1); // sub will be "ello"

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

例如:String s = "hello"; boolean isStartsWith = s.startsWith("he"); // isStartsWith will be true

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

例如:String s = "hello"; boolean isEndsWith = s.endsWith("lo"); // isEndsWith will be true

15. valueOf(Object obj):将对象转换为字符串。

例如:int num = 123; String str = String.valueOf(num); // str will be "123"

以上就是必须知道的Java中字符串处理函数,掌握这些函数,可以大大提高字符串处理的效率。