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

Java中常用字符串函数及其演示

发布时间:2023-07-27 14:36:54

Java中常用字符串函数有很多,以下列举一些常用的字符串函数及其演示:

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

String str = "Hello world";
int len = str.length();
System.out.println("字符串长度为:" + len);

2. charAt():获取指定索引位置的字符

String str = "Hello";
char c = str.charAt(0);
System.out.println("索引0位置的字符为:" + c);

3. substring():截取字符串的一部分

String str = "Hello world";
String sub = str.substring(0, 5);
System.out.println("截取的子字符串为:" + sub);

4. split():按照指定的分隔符将字符串拆分为字符串数组

String str = "Hello,world";
String[] arr = str.split(",");
for (String s : arr) {
    System.out.println("拆分的字符串为:" + s);
}

5. replace():将字符串中的指定字符或字符串替换为其他字符或字符串

String str = "Hello world";
String replaceStr = str.replace("world", "Java");
System.out.println("替换后的字符串为:" + replaceStr);

6. concat():将两个字符串连接起来

String str1 = "Hello";
String str2 = "world";
String concatStr = str1.concat(str2);
System.out.println("连接后的字符串为:" + concatStr);

7. toUpperCase():将字符串转换为大写

String str = "hello world";
String upperCaseStr = str.toUpperCase();
System.out.println("转换为大写的字符串为:" + upperCaseStr);

8. toLowerCase():将字符串转换为小写

String str = "HELLO WORLD";
String lowerCaseStr = str.toLowerCase();
System.out.println("转换为小写的字符串为:" + lowerCaseStr);

9. trim():去除字符串的前后空格

String str = "  Hello world  ";
String trimStr = str.trim();
System.out.println("去除空格后的字符串为:" + trimStr);

10. indexOf():获取指定字符或字符串在字符串中 次出现的索引位置

String str = "Hello world";
int index = str.indexOf("o");
System.out.println("      次出现的索引位置为:" + index);

这些是Java中常用的字符串函数,通过它们我们可以实现对字符串的各种操作。