JAVA中常用的字符串处理函数
Java是面向对象的编程语言,字符串处理函数是其中非常常用的部分。字符串是由零个或多个字符组成的序列,在Java中,可以使用String类来处理字符串。字符串处理是Java程序开发中非常重要的一部分,下面是Java中常用的字符串处理函数。
1. length()
length()函数用于获取字符串的长度。语法:str.length(),其中str是要获取长度的字符串。示例:
String str = "Hello World"; int length = str.length(); System.out.println(length); //输出:11
2. concat()
concat()函数用于连接两个字符串,返回新的字符串。语法:str1.concat(str2),其中str1、str2是要连接的两个字符串。示例:
String str1 = "Hello"; String str2 = "World"; String result = str1.concat(str2); System.out.println(result); //输出:HelloWorld
3. indexOf()
indexOf()函数用于查找指定字符或者子字符串在字符串中 次出现的位置。语法:str.indexOf(substr),其中str是要查找的字符串,substr是要查找的子字符串。示例:
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); //输出:6
4. charAt()
charAt()函数用于获取字符串中指定位置的字符。语法:str.charAt(index),其中str是要获取字符的字符串,index是字符的位置。示例:
String str = "Hello World"; char ch = str.charAt(1); System.out.println(ch); //输出:e
5. substring()
substring()函数用于获取字符串的子字符串。语法:str.substring(beginIndex)或者str.substring(beginIndex, endIndex),其中str是要获取子字符串的字符串,beginIndex和endIndex是子字符串的开始和结束位置。示例:
String str = "Hello World"; String subStr1 = str.substring(6); String subStr2 = str.substring(0, 5); System.out.println(subStr1); //输出:World System.out.println(subStr2); //输出:Hello
6. trim()
trim()函数用于去除字符串首尾的空格,返回新的字符串。语法:str.trim(),其中str是要去除空格的字符串。示例:
String str1 = " Hello World "; String str2 = str1.trim(); System.out.println(str2); //输出:Hello World
7. toUpperCase()和toLowerCase()
toUpperCase()函数用于将字符串中的所有字符转化为大写字母,返回新的字符串。toLowerCase()函数用于将字符串中的所有字符转化为小写字母,返回新的字符串。语法:str.toUpperCase()和str.toLowerCase(),其中str是要转化的字符串。示例:
`
String str = "Hello World";
String upper = str.toUpperCase();
String lower = str.toLowerCase();
System.out.println(upper); //输出:HELLO WORLD
System.out.println(lower); //输出:hello world
