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

Java中的字符串函数:如何对字符串进行操作?

发布时间:2023-10-01 19:39:54

Java中的字符串是不可变对象,这意味着一旦创建了一个字符串对象,它的内容就不能被修改。在处理字符串时,我们通常使用字符串函数来对字符串进行操作,以下是一些常见的字符串函数:

1. length():返回字符串的长度。

String str = "Hello World";
int len = str.length();  // len的值为11

2. charAt(int index):返回字符串中给定索引位置的字符。

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

3. substring(int beginIndex, int endIndex):返回字符串中指定范围的子字符串。

String str = "Hello World";
String subStr = str.substring(6, 11);  // subStr的值为"World"

4. toUpperCase()toLowerCase():将字符串转换为全大写或全小写。

String str = "Hello World";
String upperCaseStr = str.toUpperCase();  // upperCaseStr的值为"HELLO WORLD"
String lowerCaseStr = str.toLowerCase();  // lowerCaseStr的值为"hello world"

5. trim():去除字符串两端的空格。

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

6. startsWith(String prefix)endsWith(String suffix):判断字符串是否以给定的前缀或后缀开始或结束。

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

7. indexOf(String str)lastIndexOf(String str):返回字符串中给定子字符串的起始位置或最后一次出现的位置。

String str = "Hello World";
int firstOccurrence = str.indexOf("o");  // firstOccurrence的值为4
int lastOccurrence = str.lastIndexOf("o");  // lastOccurrence的值为7

8. replace(char oldChar, char newChar)replace(CharSequence target, CharSequence replacement):将字符串中的指定字符或子字符串替换为新的字符或字符串。

String str = "Hello World";
String replacedStr = str.replace("l", "r");  // replacedStr的值为"Herro Worrd"

9. split(String regex):将字符串按照给定的正则表达式分割为字符串数组。

String str = "Hello,World";
String[] splitStr = str.split(",");  // splitStr的值为["Hello", "World"]

10. concat(String str):将指定字符串连接到原字符串的末尾。

String str1 = "Hello";
String str2 = "World";
String concatenatedStr = str1.concat(str2);  // concatenatedStr的值为"HelloWorld"

这些只是Java中字符串函数的一小部分,还有很多其他的函数可以对字符串进行操作。在实际开发中,根据具体的需求选择适当的字符串函数来操作字符串,可以更有效地处理字符串。