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

Java的String类中有哪些常用函数?如何使用这些函数?

发布时间:2023-10-19 09:22:02

Java的String类中有很多常用函数,下面是其中一部分的介绍及使用方法:

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

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

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

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

3. substring(int beginIndex, int endIndex):返回指定的子串,开始索引处的字符包括在内,而结束索引处的字符不包括在内。例如:

   String str = "Hello World!";
   String sub = str.substring(6, 11); // sub的值为"World"
   

4. equals(Object obj):判断字符串与指定的对象是否相等。例如:

   String str1 = "Hello";
   String str2 = "Hello";
   boolean isEqual = str1.equals(str2); // isEqual的值为true
   

5. compareTo(String anotherString):按字典顺序比较两个字符串。若字符串相等,返回0;若当前字符串小于参数字符串,返回负数;如果当前字符串大于参数字符串,返回正数。例如:

   String str1 = "hello";
   String str2 = "world";
   int compareResult = str1.compareTo(str2); // compareResult的值为-5
   

6. indexOf(String str):返回 次出现指定子串的索引位置,若该子串不存在,则返回-1。例如:

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

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

   String str = "Hello World!";
   String upper = str.toUpperCase(); // upper的值为"HELLO WORLD!"
   String lower = str.toLowerCase(); // lower的值为"hello world!"
   

8. replace(CharSequence target, CharSequence replacement):将指定的字符序列替换为另一个字符序列。例如:

   String str = "Hello World!";
   String replacedStr = str.replace("o", "*"); // replacedStr的值为"Hell* W*rld!"
   

9. split(String regex):将字符串分割成字符串数组。例如:

   String str = "Hello World!";
   String[] strArr = str.split(" "); // strArr的值为["Hello", "World!"]
   

10. trim():去除字符串前后的空白字符。例如:

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

这只是String类中的一小部分常用函数,它们可以帮助我们对字符串进行各种常见的操作。使用这些函数时,只需要通过对String对象调用相应的方法,并传入所需的参数即可。