如何在 Java 中修剪 StringBuffer 中的空格?
Java 的 String 类(java.lang 包的一部分)表示一组字符。Java 程序中的所有字符串字面量,例如“abc”,都作为此类的实例实现。字符串对象是不可变的,一旦创建了字符串对象,就无法更改其值。如果尝试这样做,则不会更改值,而是会创建一个具有所需值的新对象,并且引用会转移到新创建的对象,留下先前未使用的对象。
当需要对字符串进行大量修改时,可以使用 StringBuffer(和 StringBuilder)类。
与字符串不同,StringBuffer 类型的对象可以反复修改,而不会留下大量新的未使用的对象。它是一个线程安全的、可变的字符序列。
示例
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append("Hello ");
buffer.append("how ");
buffer.append("are ");
buffer.append("you");
System.out.println("Contents of the string buffer: "+buffer);
}
}输出
Contents of the string buffer: Hello how are you
修剪空格
StringBuffer() 没有提供任何方法来删除其内容之间的空格。
String 类的 trim() 方法首先复制当前字符串,删除其开头和结尾的空格,然后返回它。
要在 StringBuffer 中删除开头和结尾的空格 -
您需要使用 toString() 方法将 StringBuffer 对象转换为 String 对象。
对结果调用 trim() 方法。
示例
public class StringBufferCapacity {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append(" Hello ");
buffer.append("how ");
buffer.append("are ");
buffer.append("you ");
System.out.println("Contents of the string buffer: "+buffer);
//Converting StringBuffer to String
String str = buffer.toString();
//Removing the leading and trailing spaces
System.out.println(str.trim());
}
}输出
Contents of the string buffer: Hello how are you
如果要完全删除 StringBuffer 中的空格,一种方法是 -
删除其开头和结尾的零。
使用 toString() 方法将 StringBuffer 对象转换为 String 值。
String 类的 split() 方法接受分隔符(以 String 格式),根据给定的分隔符将给定字符串拆分为字符串数组。
使用此方法拆分上一步中获得的字符串。
将数组中每个元素追加到另一个 StringBuffer。
示例
public class StringBufferCapacity {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append(" Hello ");
buffer.append("how ");
buffer.append("are ");
buffer.append("you ");
System.out.println("Contents of the string buffer: "+buffer);
//Converting StringBuffer to String
String str = buffer.toString();
//Removing the leading and trailing spaces
str = str.trim();
//Splitting the String
String array[] = str.split(" ");
//Appending each value to a buffer
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println("Result: "+result);
}
}输出
Contents of the string buffer: Hello how are you Result: Hellohowareyou
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP