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

Java字符串常用函数及使用方法

发布时间:2023-06-20 05:51:58

Java中的字符串常用函数有很多,下面列举一些常用的函数及其使用方法。

1. length()方法

length()方法用于返回字符串的长度,例如:

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

2. charAt()方法

charAt()方法用于返回字符串中指定位置的字符,例如:

String str = "Hello World";
char ch = str.charAt(1); // ch = 'e'

3. substring()方法

substring()方法用于截取字符串中的一部分,例如:

String str = "Hello World";
String s = str.substring(1, 4); // s = "ell"

4. equals()方法

equals()方法用于比较两个字符串是否相等,例如:

String str1 = "Hello World";
String str2 = "hello world";
boolean b = str1.equals(str2); // b = false

5. toUpperCase()和toLowerCase()方法

toUpperCase()方法用于将字符串中的所有字符转换为大写,toLowerCase()方法用于将字符串中的所有字符转换为小写,例如:

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

6. indexOf()方法

indexOf()方法用于查找字符串中指定字符或子串的位置,例如:

String str = "Hello World";
int index1 = str.indexOf('o'); // index1 = 4
int index2 = str.indexOf("Wo"); // index2 = 6

7. replace()方法

replace()方法用于将字符串中的指定字符或子串替换为另一个字符或子串,例如:

String str = "Hello World";
String s = str.replace("o", "a"); // s = "Hella Warld"

8. startsWith()和endsWith()方法

startsWith()方法用于判断字符串是否以指定的字符或子串开始,endsWith()方法用于判断字符串是否以指定的字符或子串结束,例如:

String str = "Hello World";
boolean b1 = str.startsWith("Hello"); // b1 = true
boolean b2 = str.endsWith("ld"); // b2 = true

9. trim()方法

trim()方法用于删除字符串两端的空格,例如:

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

以上就是Java字符串常用函数及使用方法的介绍,希望对大家有所帮助。