字符串相关的Java函数及其用法
发布时间:2023-08-24 12:56:56
字符串相关的Java函数及其用法共有很多,下面只介绍其中一部分常用的函数及其用法。
1. length():获取字符串的长度。
例:
String str = "hello"; int len = str.length(); // 返回5
2. charAt():获取字符串中指定位置的字符,索引从0开始。
例:
String str = "hello"; char c = str.charAt(2); // 返回l
3. equals():比较两个字符串是否相等。
例:
String str1 = "hello"; String str2 = "world"; boolean isEqual = str1.equals(str2); // 返回false
4. indexOf():返回指定字符在字符串中第一次出现的位置,若未找到则返回-1。
例:
String str = "hello, world";
int position = str.indexOf('o'); // 返回4
int position2 = str.indexOf('x'); // 返回-1
5. substring():截取指定位置的子串。
例:
String str = "hello, world"; String subStr = str.substring(2, 7); // 返回llo,
6. trim():去除字符串两端的空白字符。
例:
String str = " hello, "; String trimmedStr = str.trim(); // 返回"hello,"
7. toLowerCase()和toUpperCase():将字符串中的字符转换为小写和大写。
例:
String str = "Hello, world"; String lowerStr = str.toLowerCase(); // 返回"hello, world" String upperStr = str.toUpperCase(); // 返回"HELLO, WORLD"
8. replace():替换字符串中的字符。
例:
String str = "hello, world";
String newStr = str.replace('o', 'i'); // 返回helli, wirld
9. split():将字符串按照指定的字符分割为字符串数组。
例:
String str = "hello,world";
String[] arr = str.split(","); // 返回["hello", "world"]
以上是字符串相关的一部分常用的Java函数及其用法,通过这些函数的使用可以完成对字符串的各种操作。
