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

JavaString函数:常用方法及示例

发布时间:2023-07-02 13:32:42

Java中的String类是不可变的,即一旦字符串被创建,它的值就无法改变。String类提供了许多常用的方法来处理字符串,下面是一些常用的方法及示例:

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

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

2. charAt(int index):返回指定位置的字符。索引从0开始。例如:

String str = "Hello World";
char c = str.charAt(4);
// c的值为'o'

3. substring(int beginIndex)和substring(int beginIndex, int endIndex):提取子字符串。 个方法返回从指定索引开始到字符串末尾的子字符串,第二个方法返回从指定索引开始到指定索引结束的子字符串。例如:

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

String sub2 = str.substring(0, 5);
// sub2的值为"Hello"

4. indexOf(char ch)和indexOf(String str):返回指定字符或字符串在源字符串中首次出现的索引位置。例如:

String str = "Hello World";
int index1 = str.indexOf('o');
// index1的值为4

int index2 = str.indexOf("or");
// index2的值为7

5. toUpperCase()和toLowerCase():将字符串转换为大写或小写。例如:

String str = "Hello World";
String upper = str.toUpperCase();
// upper的值为"HELLO WORLD"

String lower = str.toLowerCase();
// lower的值为"hello world"

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

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

7. equals(Object obj)和equalsIgnoreCase(String str):比较两个字符串是否相等,第二个方法忽略大小写。例如:

String str1 = "Hello World";
String str2 = "hello world";
boolean result1 = str1.equals(str2);
// result1的值为false

boolean result2 = str1.equalsIgnoreCase(str2);
// result2的值为true

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

String str = "Hello World";
boolean start = str.startsWith("He");
// start的值为true

boolean end = str.endsWith("ld");
// end的值为true

9. replace(char oldChar, char newChar)和replace(CharSequence target, CharSequence replacement):将字符或字符串替换为指定的字符或字符串。例如:

String str = "Hello World";
String replaced1 = str.replace('o', 'e');
// replaced1的值为"Helle Werld"

String replaced2 = str.replace("World", "Universe");
// replaced2的值为"Hello Universe"

这些只是String类提供的一些常用方法的示例,还有许多其他方法可用于字符串的操作和处理。通过使用这些方法,您可以更轻松地操作和处理字符串。