Java 中String类的常用方法

发布于:2025-09-11 ⋅ 阅读:(21) ⋅ 点赞:(0)

Java 中的 String 类提供了丰富的方法用于字符串操作,以下是最常用的一些方法分类总结:

一、获取字符串信息

  1. length():返回字符串长度(字符个数)

    String s = "hello";
    int len = s.length(); // len = 5
    
  2. charAt(int index):返回指定索引(从0开始)的字符

    char c = "hello".charAt(1); // c = 'e'
    
  3. indexOf(String str):返回子串 str 首次出现的索引,未找到返回 -1

    int idx = "hello world".indexOf("lo"); // idx = 3
    
  4. lastIndexOf(String str):返回子串 str 最后出现的索引

    int idx = "ababa".lastIndexOf("aba"); // idx = 2
    

二、字符串比较

  1. equals(Object obj):判断两个字符串内容是否完全相同(区分大小写)

    "abc".equals("ABC"); // false
    
  2. equalsIgnoreCase(String str):忽略大小写比较内容

    "abc".equalsIgnoreCase("ABC"); // true
    
  3. compareTo(String str):按字典顺序比较,返回差值(正数:当前串大;负数:参数串大;0:相等)

    "apple".compareTo("banana"); // 负数('a' < 'b')
    

三、字符串截取与拆分

  1. substring(int beginIndex):从 beginIndex 截取到末尾

    "hello".substring(2); // "llo"
    
  2. substring(int beginIndex, int endIndex):截取 [beginIndex, endIndex) 范围的子串(左闭右开)

    "hello".substring(1, 4); // "ell"
    
  3. split(String regex):按正则表达式拆分字符串,返回字符串数组

    String[] parts = "a,b,c".split(","); // ["a", "b", "c"]
    

四、字符串修改(注意:String 是不可变的,以下方法返回新字符串)

  1. toLowerCase() / toUpperCase():转为全小写 / 全大写

    "Hello".toLowerCase(); // "hello"
    "Hello".toUpperCase(); // "HELLO"
    
  2. trim():去除首尾空白字符(空格、换行、制表符等)

    "  hello  ".trim(); // "hello"
    
  3. replace(char oldChar, char newChar):替换所有指定字符

    "hello".replace('l', 'x'); // "hexxo"
    
  4. replace(String oldStr, String newStr):替换所有指定子串

    "hello world".replace("world", "java"); // "hello java"
    
  5. concat(String str):拼接字符串(等价于 + 运算符)

    "hello".concat(" world"); // "hello world"
    

五、判断字符串特性

  1. startsWith(String prefix):判断是否以指定前缀开头

    "hello".startsWith("he"); // true
    
  2. endsWith(String suffix):判断是否以指定后缀结尾

    "hello.txt".endsWith(".txt"); // true
    
  3. isEmpty():判断字符串是否为空(长度为0)

    "".isEmpty(); // true
    "a".isEmpty(); // false
    
  4. contains(CharSequence s):判断是否包含指定子串

    "hello".contains("ll"); // true
    

六、其他常用方法

  1. toCharArray():将字符串转为字符数组

    char[] arr = "hello".toCharArray(); // ['h','e','l','l','o']
    
  2. valueOf(xxx):静态方法,将其他类型转为字符串(常用)

    String.valueOf(123); // "123"
    String.valueOf(true); // "true"
    
  3. format(String format, Object... args):静态方法,格式化字符串(类似 printf

    String.format("Name: %s, Age: %d", "Tom", 20); // "Name: Tom, Age: 20"
    

注意事项

  • String 是不可变对象,所有修改方法都会返回新的字符串,原字符串不变。
  • 频繁修改字符串时,建议使用 StringBuilderStringBuffer 以提高效率。

网站公告

今日签到

点亮在社区的每一天
去签到