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

Java中常用的字符串函数及其应用举例

发布时间:2023-06-25 17:00:38

Java中常用的字符串函数有很多,其中一些常用的有:

1. length()函数

这个函数用于获取字符串的长度,例如:

String s = "Hello, World!";

int len = s.length(); // len的值为13

2. charAt()函数

这个函数用于获取字符串中指定位置的字符,例如:

String s = "Hello, World!";

char c = s.charAt(4); // c的值为'o'

3. substring()函数

这个函数用于获取字符串中的子串,例如:

String s = "Hello, World!";

String sub = s.substring(7); // sub的值为"World!"

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

4. indexOf()函数

这个函数用于查找字符串中指定字符或子串的位置,例如:

String s = "Hello, World!";

int pos = s.indexOf('o'); // pos的值为4

int pos2 = s.indexOf("World"); // pos2的值为7

5. equals()函数

这个函数用于比较两个字符串是否相同,例如:

String s1 = "Hello, World!";

String s2 = "hello, world!";

boolean isEqual = s1.equals(s2); // isEqual的值为false

6. startsWith()函数和endsWith()函数

这两个函数分别用于判断字符串是否以指定的字符或子串开头或结尾,例如:

String s = "Hello, World!";

boolean starts = s.startsWith("He"); // starts的值为true

boolean ends = s.endsWith("!"); // ends的值为true

7. toUpperCase()函数和toLowerCase()函数

这两个函数分别用于将字符串中的字母转换成大写或小写,例如:

String s = "Hello, World!";

String upper = s.toUpperCase(); // upper的值为"HELLO, WORLD!"

String lower = s.toLowerCase(); // lower的值为"hello, world!"

这些函数在实际开发中使用非常频繁。例如,我们可以使用length()函数来判断用户输入的字符串是否超出了最大长度限制;使用substring()函数来获取用户输入的用户名或密码的前几个字符;使用indexOf()函数来判断一个字符串中是否包含特定的子串;使用equals()函数来判断两个字符串是否相等等等。总之,字符串函数是Java开发中不可或缺的工具之一。