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

Java中常用的字符处理函数及使用方法

发布时间:2023-06-26 01:50:01

Java中常用的字符处理函数及使用方法

Java中String类是常用的字符串处理类,它提供了很多操作字符串的方法。本文将介绍Java中常见的字符处理函数及使用方法,帮助大家更好地理解Java的字符串处理功能。

1. charAt(int index)

函数介绍:返回指定索引位置的字符。

使用方法:String str = "hello"; char ch = str.charAt(2); // ch='l'

注:索引从0开始。

2. length()

函数介绍:返回一个字符串的长度。

使用方法:String str = "hello"; int len = str.length(); // len=5

3. toCharArray()

函数介绍:将一个字符串转换为字符数组。

使用方法:String str = "hello"; char[] chArr = str.toCharArray(); //chArr={'h','e','l','l','o'}

4. substring(int beginIndex)

函数介绍:返回一个从指定索引开始到结尾的子字符串。

使用方法:String str = "hello"; String subStr = str.substring(2); // subStr='llo'

注:beginIndex从0开始。

5. substring(int beginIndex, int endIndex)

函数介绍:返回一个从beginIndex开始到endIndex的子字符串(包括beginIndex但不包括endIndex)。

使用方法:String str = "hello"; String subStr = str.substring(1, 4); // subStr='ell'

6. indexOf(char ch)

函数介绍:返回指定字符在字符串中 次出现的索引位置,如果没有找到,返回-1。

使用方法:String str = "hello"; int index = str.indexOf('l'); // index=2

7. indexOf(String str)

函数介绍:返回指定字符串在此字符串中 次出现的索引位置,如果没有找到,返回-1。

使用方法:String str = "hello"; int index = str.indexOf("lo"); // index=3

8. lastIndexOf(char ch)

函数介绍:返回指定字符在此字符串中最后一次出现的索引位置,如果没有找到,返回-1。

使用方法:String str = "hello world"; int index = str.lastIndexOf('o'); // index=7

9. lastIndexOf(String str)

函数介绍:返回指定字符串在此字符串中最后一次出现的索引位置,如果没有找到,返回-1。

使用方法:String str = "hello, hello, world"; int index = str.lastIndexOf("lo"); // index=16

10. startsWith(String prefix)

函数介绍:测试此字符串是否以指定的前缀开头。

使用方法:String str = "hello world"; boolean result = str.startsWith("hello"); // result=true

11. endsWith(String suffix)

函数介绍:测试此字符串是否以指定的后缀结尾。

使用方法:String str = "hello world"; boolean result = str.endsWith("world"); // result=true

12. replace(char oldChar, char newChar)

函数介绍:将字符串中的指定字符 替换为新的字符。

使用方法:String str = "hello world"; String newStr = str.replace('l', 'L'); // newStr="heLLo worLd"

13. replaceAll(String regex, String replacement)

函数介绍:使用指定的 字符串替换 文本中的每个匹配正则表达式的子字符串。

使用方法: String str = "hello world"; String newStr = str.replaceAll("o", "O"); // newStr="hellO wOrld"

14. trim()

函数介绍:返回一个去除了空格的字符串。

使用方法:String str = " hello world "; String newStr = str.trim(); // newStr="hello world"

注:没有去掉中间的空格。

15. toLowerCase()

函数介绍:将此字符串中的所有字符转换为小写字母。

使用方法:String str = "Hello World"; String newStr = str.toLowerCase(); // newStr="hello world"

16. toUpperCase()

函数介绍:将此字符串中的所有字符转换为大写字母。

使用方法:String str = "Hello World"; String newStr = str.toUpperCase(); // newStr="HELLO WORLD"

17. split(String regex)

函数介绍:根据正则表达式将此字符串分隔为一个字符串数组。

使用方法: String str = "hello,world"; String[] arr = str.split(","); // arr={"hello", "world"}

以上就是Java中常用的字符处理函数及使用方法,希望大家能够掌握这些方法,更好地编写Java程序。