欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Java中的String、StringBuilder、StringBuffer

Java中的String、StringBuilder、StringBuffer

2024/10/25 23:38:23 来源:https://blog.csdn.net/Broken_x/article/details/141685218  浏览:    关键词:Java中的String、StringBuilder、StringBuffer

        在Java中,StringStringBuilder 和 StringBuffer 是处理字符串的三个常用类,它们各有特点和适用场景。以下是对这三个类的详细解释、常用方法的代码示例以及它们之间的区别和适用场景。

String

String 类表示不可变的字符序列。一旦创建,String 对象的内容不能被改变。

常用方法示例:

public class StringExample {public static void main(String[] args) {String str = "Hello, World!";// length(): 返回字符串的长度System.out.println("Length: " + str.length()); // 输出: 13// charAt(int index): 返回指定索引处的字符System.out.println("Char at index 7: " + str.charAt(7)); // 输出: W// substring(int beginIndex): 返回从指定索引开始到字符串末尾的子字符串System.out.println("Substring from index 7: " + str.substring(7)); // 输出: World!// substring(int beginIndex, int endIndex): 返回从指定索引开始到指定索引结束的子字符串System.out.println("Substring from index 7 to 12: " + str.substring(7, 12)); // 输出: World// concat(String str): 连接字符串System.out.println("Concatenated string: " + str.concat(" Welcome")); // 输出: Hello, World! Welcome// replace(char oldChar, char newChar): 替换字符System.out.println("Replaced string: " + str.replace('o', 'a')); // 输出: Hella, Warld!// toUpperCase(): 将字符串转换为大写System.out.println("Uppercase string: " + str.toUpperCase()); // 输出: HELLO, WORLD!// toLowerCase(): 将字符串转换为小写System.out.println("Lowercase string: " + str.toLowerCase()); // 输出: hello, world!// trim(): 去除字符串两端的空白字符String strWithSpaces = "  Hello, World!  ";System.out.println("Trimmed string: " + strWithSpaces.trim()); // 输出: Hello, World!// indexOf(String str): 返回指定子字符串第一次出现的索引System.out.println("Index of 'World': " + str.indexOf("World")); // 输出: 7// lastIndexOf(String str): 返回指定子字符串最后一次出现的索引System.out.println("Last index of 'o': " + str.lastIndexOf('o')); // 输出: 8// contains(CharSequence s): 判断字符串是否包含指定的字符序列System.out.println("Contains 'World': " + str.contains("World")); // 输出: true// startsWith(String prefix): 判断字符串是否以指定的前缀开始System.out.println("Starts with 'Hello': " + str.startsWith("Hello")); // 输出: true// endsWith(String suffix): 判断字符串是否以指定的后缀结束System.out.println("Ends with 'World!': " + str.endsWith("World!")); // 输出: true// equals(Object anObject): 判断字符串是否与指定对象相等System.out.println("Equals 'Hello, World!': " + str.equals("Hello, World!")); // 输出: true// compareTo(String anotherString): 按字典顺序比较两个字符串System.out.println("Compare to 'Hello, World!': " + str.compareTo("Hello, World!")); // 输出: 0}
}

StringBuilder

StringBuilder 类表示可变的字符序列。与 String 不同,StringBuilder 对象的内容可以被修改。

常用方法示例:

public class StringBuilderExample {public static void main(String[] args) {StringBuilder sb = new StringBuilder("Hello");// append(String str): 追加字符串sb.append(", World!");System.out.println("Appended string: " + sb.toString()); // 输出: Hello, World!// insert(int offset, String str): 在指定位置插入字符串sb.insert(5, " there");System.out.println("Inserted string: " + sb.toString()); // 输出: Hello there, World!// delete(int start, int end): 删除指定范围内的字符sb.delete(5, 11);System.out.println("Deleted string: " + sb.toString()); // 输出: Hello, World!// reverse(): 反转字符串sb.reverse();System.out.println("Reversed string: " + sb.toString()); // 输出: !dlroW ,olleH// setCharAt(int index, char ch): 设置指定索引处的字符sb.reverse().setCharAt(7, 'W');System.out.println("Set char at index 7: " + sb.toString()); // 输出: Hello, World!// length(): 返回字符串的长度System.out.println("Length: " + sb.length()); // 输出: 13// capacity(): 返回当前容量System.out.println("Capacity: " + sb.capacity()); // 输出: 21// ensureCapacity(int minimumCapacity): 确保容量至少等于指定的最小值sb.ensureCapacity(50);System.out.println("Ensured capacity: " + sb.capacity()); // 输出: 50// charAt(int index): 返回指定索引处的字符System.out.println("Char at index 7: " + sb.charAt(7)); // 输出: W// substring(int start): 返回从指定索引开始到字符串末尾的子字符串System.out.println("Substring from index 7: " + sb.substring(7)); // 输出: World!// substring(int start, int end): 返回从指定索引开始到指定索引结束的子字符串System.out.println("Substring from index 7 to 12: " + sb.substring(7, 12)); // 输出: World}
}

StringBuffer

StringBuffer 类也表示可变的字符序列,但与 StringBuilder 不同,StringBuffer 是线程安全的。

常用方法示例:

public class StringBufferExample {public static void main(String[] args) {StringBuffer sbuf = new StringBuffer("Hello");// append(String str): 追加字符串sbuf.append(", World!");System.out.println("Appended string: " + sbuf.toString()); // 输出: Hello, World!// insert(int offset, String str): 在指定位置插入字符串sbuf.insert(5, " there");System.out.println("Inserted string: " + sbuf.toString()); // 输出: Hello there, World!// delete(int start, int end): 删除指定范围内的字符sbuf.delete(5, 11);System.out.println("Deleted string: " + sbuf.toString()); // 输出: Hello, World!// reverse(): 反转字符串sbuf.reverse();System.out.println("Reversed string: " + sbuf.toString()); // 输出: !dlroW ,olleH// setCharAt(int index, char ch): 设置指定索引处的字符sbuf.reverse().setCharAt(7, 'W');System.out.println("Set char at index 7: " + sbuf.toString()); // 输出: Hello, World!// length(): 返回字符串的长度System.out.println("Length: " + sbuf.length()); // 输出: 13// capacity(): 返回当前容量System.out.println("Capacity: " + sbuf.capacity()); // 输出: 21// ensureCapacity(int minimumCapacity): 确保容量至少等于指定的最小值sbuf.ensureCapacity(50);System.out.println("Ensured capacity: " + sbuf.capacity()); // 输出: 50// charAt(int index): 返回指定索引处的字符System.out.println("Char at index 7: " + sbuf.charAt(7)); // 输出: W// substring(int start): 返回从指定索引开始到字符串末尾的子字符串System.out.println("Substring from index 7: " + sbuf.substring(7)); // 输出: World!// substring(int start, int end): 返回从指定索引开始到指定索引结束的子字符串System.out.println("Substring from index 7 to 12: " + sbuf.substring(7, 12)); // 输出: World}
}

三者的区别

  • String

    • 不可变性:一旦创建,内容不能被改变。
    • 线程安全:由于不可变性,天然线程安全。
    • 性能:适用于不频繁修改字符串的场景,频繁修改会导致大量对象创建和垃圾回收。
  • StringBuilder

    • 可变性:内容可以被修改。
    • 非线程安全:适用于单线程环境。
    • 性能:在单线程环境下性能优于 StringBuffer,适用于频繁修改字符串的场景。
  • StringBuffer

    • 可变性:内容可以被修改。
    • 线程安全:所有公共方法都是同步的,适用于多线程环境。
    • 性能:在多线程环境下性能略低于 StringBuilder,但在单线程环境下性能也较差。

总结

  • 使用 String 适用于字符串不频繁修改且不需要线程安全的场景。
  • 使用 StringBuilder 适用于单线程环境下需要频繁修改字符串的场景。
  • 使用 StringBuffer 适用于多线程环境下需要频繁修改字符串的场景。

        通过以上解释和示例代码,我们可以清楚地了解到 String   StringBuilder   StringBuffer 的区别和使用场景。选择合适的类可以提高代码的性能和可维护性。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com