String类的常用方法?

236 阅读2分钟

String 类是 Java 中用于表示字符串的类,它提供了丰富的方法来进行字符串操作。以下是 String 类的一些常用方法:

  1. 获取字符串长度:

    • int length(): 返回字符串的长度。

      String str = "Hello, World!";
      int length = str.length(); // 返回 13
      
  2. 获取指定位置的字符:

    • char charAt(int index): 返回字符串中指定位置的字符。

      char firstChar = str.charAt(0); // 返回 'H'
      
  3. 获取子串:

    • String substring(int beginIndex): 返回从指定位置开始到字符串末尾的子串。

    • String substring(int beginIndex, int endIndex): 返回从指定位置开始到指定位置结束的子串,不包含结束位置的字符。

      String sub1 = str.substring(7);    // 返回 "World!"
      String sub2 = str.substring(7, 12); // 返回 "World"
      
  4. 拼接字符串:

    • String concat(String str): 将指定字符串连接到此字符串的末尾。

      String greeting = "Hello";
      String message = greeting.concat(", World!"); // 返回 "Hello, World!"
      
  5. 比较字符串:

    • boolean equals(Object obj): 比较字符串是否相等。

    • boolean equalsIgnoreCase(String anotherString): 比较字符串是否相等,忽略大小写。

    • int compareTo(String anotherString): 按字典顺序比较两个字符串。

    • boolean startsWith(String prefix): 判断字符串是否以指定的前缀开始。

    • boolean endsWith(String suffix): 判断字符串是否以指定的后缀结束。

      String str1 = "hello";
      String str2 = "HELLO";
      boolean isEqual = str1.equals(str2); // 返回 false
      boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // 返回 true
      int compareResult = str1.compareTo(str2); // 返回负数
      boolean startsWithHello = str1.startsWith("Hello"); // 返回 false
      boolean endsWithLo = str1.endsWith("lo"); // 返回 true
      
  6. 查找子串:

    • int indexOf(String str): 返回指定子字符串在字符串中第一次出现的位置。

    • int indexOf(String str, int fromIndex): 从指定位置开始,返回指定子字符串在字符串中第一次出现的位置。

    • int lastIndexOf(String str): 返回指定子字符串在字符串中最右边出现的位置。

    • int lastIndexOf(String str, int fromIndex): 从指定位置开始,返回指定子字符串在字符串中最右边出现的位置。

      String text = "Java is easy, Java is fun";
      int firstJavaIndex = text.indexOf("Java"); // 返回 0
      int secondJavaIndex = text.indexOf("Java", 1); // 返回 12
      int lastJavaIndex = text.lastIndexOf("Java"); // 返回 12
      
  7. 替换字符串:

    • String replace(char oldChar, char newChar): 将字符串中所有的 oldChar 替换为 newChar。

    • String replace(CharSequence target, CharSequence replacement): 将字符串中所有的 target 替换为 replacement。

      String original = "Hello, World!";
      String replaced = original.replace('l', 'z'); // 返回 "Hezzo, Worzd!"
      
  8. 去除空格:

    • String trim(): 返回字符串的副本,去除字符串开头和结尾的空格。

      String withSpaces = "   Hello, World!   ";
      String withoutSpaces = withSpaces.trim(); // 返回 "Hello, World!"
      
  9. 转换大小写:

    • String toLowerCase(): 将字符串中的所有字符转换为小写。

    • String toUpperCase(): 将字符串中的所有字符转换为大写。

      String lowercase = "Hello, World!".toLowerCase(); // 返回 "hello, world!"
      String uppercase = "Hello, World!".toUpperCase(); // 返回 "HELLO, WORLD!"
      
  10. 判断是否包含:

  • boolean contains(CharSequence sequence): 判断字符串是否包含指定的子序列。

    String sentence = "Java is a powerful programming language.";
    boolean containsJava = sentence.contains("Java"); // 返回 true