Java中字符串处理的函数-10个相关函数
Java中字符串处理的函数非常丰富,常用的有以下10个相关函数:
1. length():返回字符串的长度。例如:String str = "hello";int len = str.length();结果为5。
2. charAt(int index):返回字符串中指定索引位置的字符。索引从0开始。例如:String str = "hello";char ch = str.charAt(1);结果为'e'。
3. substring(int beginIndex, int endIndex):返回字符串中从指定开始索引到结束索引的子字符串。例如:String str = "hello";String subStr = str.substring(1, 4);结果为"ell"。
4. indexOf(String str):返回字符串中指定字符串 次出现的索引位置。如果找不到指定字符串,则返回-1。例如:String str = "hello";int index = str.indexOf("l");结果为2。
5. replace(CharSequence target, CharSequence replacement):将字符串中的目标字符串替换为指定字符串。例如:String str = "hello";String newStr = str.replace("l", "X");结果为"heXXo"。
6. toLowerCase():将字符串中的所有字母转换为小写。例如:String str = "Hello";String newStr = str.toLowerCase();结果为"hello"。
7. toUpperCase():将字符串中的所有字母转换为大写。例如:String str = "Hello";String newStr = str.toUpperCase();结果为"HELLO"。
8. trim():去除字符串中的前导和尾部空格。例如:String str = " hello ";String newStr = str.trim();结果为"hello"。
9. split(String regex):将字符串按照指定的正则表达式进行拆分,并返回拆分后的字符串数组。例如:String str = "hello world";String[] arr = str.split(" ");结果为["hello", "world"]。
10. contains(CharSequence sequence):判断字符串是否包含指定的字符序列。例如:String str = "hello";boolean isContains = str.contains("ell");结果为true。
这些函数能够满足大部分字符串处理的需求,如获取字符串长度、获取指定位置字符、提取子字符串、查找字符串、替换字符串、转换为大小写、去除空格、拆分字符串以及判断是否包含指定字符序列等。在实际的开发中,根据具体的需求选择合适的函数进行字符串处理。
