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

如何在Java中编写函数来处理字符串?

发布时间:2023-11-25 17:32:12

在Java中,可以使用字符串类的方法来处理字符串。以下是一些常用的字符串处理函数的示例:

1. length() - 获取字符串的长度。

String str = "Hello World";
int length = str.length(); // length = 11

2. charAt() - 获取给定索引位置上的字符。

String str = "Hello";
char ch = str.charAt(0); // ch = 'H'

3. substring() - 提取字符串的子串。

String str = "Hello World";
String subStr = str.substring(6); // subStr = "World"

4. indexOf() - 查找子串在字符串中的 个匹配位置。

String str = "Hello World";
int index = str.indexOf("World"); // index = 6

5. replace() - 替换字符串中的匹配内容。

String str = "Hello World";
String newStr = str.replace("World", "Java"); // newStr = "Hello Java"

6. split() - 根据给定的分隔符拆分字符串。

String str = "Hello,World";
String[] words = str.split(","); // words = ["Hello", "World"]

7. toLowerCase() / toUpperCase() - 将字符串转换为小写 / 大写。

String str = "Hello World";
String lowerStr = str.toLowerCase(); // lowerStr = "hello world"
String upperStr = str.toUpperCase(); // upperStr = "HELLO WORLD"

8. trim() - 去除字符串两端的空格。

String str = "   Hello World   ";
String trimmedStr = str.trim(); // trimmedStr = "Hello World"

9. startsWith() / endsWith() - 判断字符串是否以给定的子串开头 / 结尾。

String str = "Hello World";
boolean startsWithHello = str.startsWith("Hello"); // startsWithHello = true
boolean endsWithWorld = str.endsWith("World"); // endsWithWorld = true

10. isEmpty() / isBlank() - 判断字符串是否为空 / 是否为空白字符。

String str1 = "";
String str2 = " ";
boolean isEmpty = str1.isEmpty(); // isEmpty = true
boolean isBlank = str2.isBlank(); // isBlank = true

以上是一些常用的字符串处理函数的示例,通过结合使用这些函数,可以完成各种字符串操作和处理。