常用的Java字符串操作函数及用法
Java字符串是开发中必不可少的一个部分,Java提供了丰富的字符串操作函数,方便我们对字符串进行处理和操作。本文将介绍以下常用的字符串操作函数及其用法。
1. length()方法
这个方法用于获取字符串的长度。示例:
String str = "hello world";
int length = str.length(); // 获取字符串长度
System.out.println(length); // 输出 11
2. charAt()方法
这个方法用于获取指定位置的字符。示例:
String str = "hello world";
char c = str.charAt(0); // 获取 个字符
System.out.println(c); // 输出 h
3. toUpperCase()和toLowerCase()方法
这两个方法用于将字符串转换为大写或小写形式。示例:
String str = "HeLLo WoRLd";
String upper = str.toUpperCase(); // 转换为大写
String lower = str.toLowerCase(); // 转换为小写
System.out.println(upper); // 输出 HELLO WORLD
System.out.println(lower); // 输出 hello world
4. substring()方法
这个方法用于获取字符串的子串。示例:
String str = "hello world";
String sub = str.substring(0, 5); // 获取从0到5的子串
System.out.println(sub); // 输出 hello
5. replace()方法
这个方法用于替换字符串中的内容。示例:
String str = "hello world";
String newStr = str.replace("world", "Java"); // 替换为 Java
System.out.println(newStr); // 输出 hello Java
6. split()方法
这个方法用于将字符串分割为数组。示例:
String str = "hello,world,Java";
String[] arr = str.split(","); // 分割为数组
for (String s : arr) {
System.out.println(s);
}
// 输出:
// hello
// world
// Java
7. trim()方法
这个方法用于去除字符串前后的空格。示例:
String str = " hello world ";
String trimStr = str.trim(); // 去除前后空格
System.out.println(trimStr); // 输出 hello world
8. startsWith()和endsWith()方法
这两个方法用于判断字符串是否以指定内容开头或结尾。示例:
String str = "hello world";
boolean starts = str.startsWith("hello"); // 判断是否以 hello 开头
boolean ends = str.endsWith("world"); // 判断是否以 world 结尾
System.out.println(starts); // 输出 true
System.out.println(ends); // 输出 true
9. isEmpty()方法
这个方法用于判断字符串是否为空。示例:
String str1 = "";
String str2 = "hello";
boolean empty1 = str1.isEmpty(); // 判断是否为空
boolean empty2 = str2.isEmpty(); // 判断是否为空
System.out.println(empty1); // 输出 true
System.out.println(empty2); // 输出 false
10. indexOf()和lastIndexOf()方法
这两个方法用于查找字符串中指定内容的位置。示例:
String str = "hello world";
int index1 = str.indexOf("w"); // 查找 w 的位置
int index2 = str.lastIndexOf("l"); // 查找最后一个 l 的位置
System.out.println(index1); // 输出 6
System.out.println(index2); // 输出 9
总结:以上就是Java中常用的字符串操作函数及其用法。在实际开发中,根据具体的需求和场景,我们可以选择使用合适的方法来处理和操作字符串。
