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

常用的Java字符串函数和用法

发布时间:2023-06-04 17:52:26

Java是一种面向对象编程语言,它提供了一套丰富的字符串处理函数。Java字符串函数是Java语言中最重要的函数之一,它们可以用于将字符串拆分、连接、比较等等。以下是Java字符串函数的常用方法和用法:

1. length():该函数用于获取字符串的长度。例如:

    String text = "Hello World";

    int len = text.length();

    // len 的值为 11

2. charAt(int index):该函数用于获取字符串指定位置的字符。例如:

    String text = "Hello World";

    char ch = text.charAt(1);

    // ch 的值为 'e'

3. substring(int beginIndex, int endIndex):该函数用于获取字符串从指定位置开始到结束位置的子字符串。例如:

    String text = "Hello World";

    String subText = text.substring(0, 5);

    // subText 的值为 "Hello"

4. indexOf(String str):该函数用于获取字符串中 次出现指定子字符串的位置。例如:

    String text = "Hello World";

    int index = text.indexOf("o");

    // index 的值为 4

5. lastIndexOf(String str):该函数用于获取字符串中最后一次出现指定子字符串的位置。例如:

    String text = "Hello World";

    int index = text.lastIndexOf("o");

    // index 的值为 7

6. equals(Object obj):该函数用于比较字符串是否相等。例如:

    String text1 = "Hello World";

    String text2 = "hello world";

    boolean isEqual = text1.equals(text2);

    // isEqual 的值为 false

7. equalsIgnoreCase(String anotherString):该函数用于比较字符串是否相等,不区分大小写。例如:

    String text1 = "Hello World";

    String text2 = "hello world";

    boolean isEqual = text1.equalsIgnoreCase(text2);

    // isEqual 的值为 true

8. toUpperCase():该函数用于将字符串转换为大写字母。例如:

    String text = "Hello World";

    String upperText = text.toUpperCase();

    // upperText 的值为 "HELLO WORLD"

9. toLowerCase():该函数用于将字符串转换为小写字母。例如:

    String text = "Hello World";

    String lowerText = text.toLowerCase();

    // lowerText 的值为 "hello world"

10. trim():该函数用于去除字符串中的空格。例如:

    String text = "    Hello World    ";

    String trimText = text.trim();

    // trimText 的值为 "Hello World"

11. split(String regex):该函数用于分解字符串,把字符串按照指定的正则表达式进行分割。例如:

    String text = "Hello,World";

    String[] splitArray = text.split(",");

    // splitArray 的值为 {"Hello", "World"}

12. replace(char oldChar, char newChar):该函数用于替换字符串中的字符。例如:

    String text = "Hello World";

    String replaceText = text.replace("l", "Z");

    // replaceText 的值为 "HeZZo WorZd"

13. startsWith(String prefix):该函数用于判断字符串是否以指定子字符串开头。例如:

    String text = "Hello World";

    boolean isStartsWith = text.startsWith("He");

    // isStartsWith 的值为 true

14. endsWith(String suffix):该函数用于判断字符串是否以指定子字符串结尾。例如:

    String text = "Hello World";

    boolean isEndsWith = text.endsWith("ld");

    // isEndsWith 的值为 true

15. valueOf(Object obj):该函数用于将不是字符串类型的数据转换成字符串类型。例如:

    int num = 10;

    String text = String.valueOf(num);

    // text 的值为 "10"

以上是Java字符串函数的常用方法和用法,通过这些函数,可以很方便地处理字符串类型的数据。