Java StringBuilder
最后修改于 2024 年 1 月 27 日
Java StringBuilder 教程展示了如何在 Java 中使用 StringBuilder。Java String 对象是不可变的;只能创建原始字符串的修改副本。当我们需要就地修改字符串时,我们使用 StringBuilder。
StringBuilder
StringBuilder 是一个可变的字符序列。 当我们想要就地修改 Java 字符串时,使用 StringBuilder。 StringBuffer 是与 StringBuilder 类似的一个线程安全等效实现。
StringBuilder 具有诸如 append、insert 或 replace 之类的方法,这些方法允许修改字符串。
Java StringBuilder 构造函数
StringBuilder 有四个构造函数
| 构造函数 | 描述 |
|---|---|
| StringBuilder() | 创建一个初始容量为 16 个字符的空字符串生成器 |
| StringBuilder(CharSequence seq) | 从 CharSequence 创建一个字符串生成器 |
| StringBuilder(int capacity) | 创建一个具有指定初始容量的空字符串生成器 |
| StringBuilder(String str) | 从指定的字符串创建一个字符串生成器 |
Java StringBuilder 是可变的
Java String 是不可变的,而 StringBuilder 是可变的。
package com.zetcode;
public class MutableImmutableEx {
public static void main(String[] args) {
var word = "rock";
var word2 = word.replace('r', 'd');
System.out.println(word2);
var builder = new StringBuilder("rock");
builder.replace(0, 1, "d");
System.out.println(builder);
}
}
该示例演示了 String 和 StringBuilder 之间的主要区别。
var word2 = word.replace('r', 'd');
Java String 有一个 replace 方法,但它不会修改原始字符串。而是创建一个修改后的副本。
var builder = new StringBuilder("rock");
builder.replace(0, 1, "d");
另一方面,StringBuilder 会就地替换字符串。
dock dock
Java StringBuilder append 方法
StringBuilder 包含多个重载的 append 方法,这些方法将一个值添加到字符串的末尾。
package com.zetcode;
import java.util.stream.LongStream;
public class StringBuilderAppendEx {
private final static long MAX_VAL = 500;
public static void main(String[] args) {
var builder = new StringBuilder();
var sum = LongStream.rangeClosed(0, MAX_VAL).sum();
LongStream.rangeClosed(1, MAX_VAL).forEach(e -> {
builder.append(e);
if (e % 10 == 0) {
builder.append("\n");
}
if (e < MAX_VAL) {
builder.append(" + ");
} else {
builder.append(" = ");
}
});
builder.append(sum);
System.out.println(builder);
}
}
该示例从数百个小字符串构建一个大字符串。 该字符串具有以下形式:1 + 2 + 3 + ... + MAX_VAL = SUM。
var builder = new StringBuilder();
创建一个空的 StringBuilder。
LongStream.rangeClosed(1, MAX_VAL).forEach(e -> {
创建一个范围为 1..MAX_VAL 的值。 我们使用 forEach 方法迭代这些值。
builder.append(e);
我们使用 append 方法将当前值附加到字符串生成器。
if (e % 10 == 0) {
builder.append("\n");
}
为了使输出适合屏幕,我们在每十个值后添加一个换行符。
if (e < MAX_VAL) {
builder.append(" + ");
} else {
builder.append(" = ");
}
在这些值之间,我们添加“+”或“=”字符。
builder.append(sum);
在字符串的末尾,我们添加值的总和。
System.out.println(builder);
最后,将字符串打印到控制台。
Java StringBuilder insert 方法
insert 方法用于将字符串插入到生成器的指定位置。
package com.zetcode;
public class StringBuilderInsertEx {
public static void main(String[] args) {
var sentence = "There is a red fox in the forest.";
var builder = new StringBuilder(sentence);
builder.insert(19, "and a wolf ");
System.out.println(builder);
}
}
该示例使用 insert 方法将字符串插入到句子中。
There is a red fox and a wolf in the forest.
我们创建了这个句子。
获取子字符串的索引
indexOf 方法返回子字符串的第一次出现,而 lastIndexOf 方法返回最后一次出现。
package com.zetcode;
public class StringBuilderIndexesEx {
public static void main(String[] args) {
var builder = new StringBuilder();
builder.append("There is a wolf in the forest. ");
builder.append("The wolf appeared very old. ");
builder.append("I never saw a wild wolf in my life.");
var term = "wolf";
int firstIdx = builder.indexOf(term);
int firstIdx2 = builder.indexOf(term, 15);
System.out.format("First occurrence of %s %d%n", term, firstIdx);
System.out.format("First occurrence of %s %d%n", term, firstIdx2);
int lastIdx = builder.lastIndexOf(term);
int lastIdx2 = builder.lastIndexOf(term, 15);
System.out.format("Last occurrence of %s %d%n", term, lastIdx);
System.out.format("Last occurrence of %s %d%n", term, lastIdx2);
System.out.println(builder);
}
}
该示例使用 indexOf 和 lastIndexOf 方法来获取“wolf”子字符串的索引。
var builder = new StringBuilder();
builder.append("There is a wolf in the forest. ");
builder.append("The wolf appeared very old. ");
builder.append("I never saw a wild wolf in my life.");
我们使用 append 方法创建一个字符串生成器。
int firstIdx = builder.indexOf(term);
我们从生成器中获取术语“wolf”的第一次出现。
int firstIdx2 = builder.indexOf(term, 15);
我们从生成器中获取术语“wolf”的第一次出现,从索引 15 开始。
int lastIdx = builder.lastIndexOf(term); int lastIdx2 = builder.lastIndexOf(term, 15);
同样,我们获得“wolf”子字符串的最后一次出现。
First occurrence of wolf 11 First occurrence of wolf 35 Last occurrence of wolf 78 Last occurrence of wolf 11 There is a wolf in the forest. The wolf appeared very old. I never saw a wild wolf in my life.
StringBuilder replace 方法
replace 方法将字符串生成器中的子字符串替换为指定的新字符串。
package com.zetcode;
public class StringBuilderReplaceEx {
public static void main(String[] args) {
var sentence = "I saw a red fox running into the forest.";
var builder = new StringBuilder(sentence);
var term = "fox";
var newterm = "dog";
int idx = builder.indexOf(term);
int len = term.length();
builder.replace(idx, idx + len, newterm);
System.out.println(builder);
}
}
该示例将子字符串“fox”替换为字符串“dog”。
int idx = builder.indexOf(term);
我们找到要替换的子字符串的起始索引。
int len = term.length();
在我们的操作中,我们需要知道子字符串的长度。
builder.replace(idx, idx + len, newterm);
我们调用 replace 方法。 第一个参数是起始索引,第二个参数是要删除的子字符串的结束索引。 第三个参数是新字符串。
Java StringBuilder 删除字符
有两种方法可以删除字符串生成器中的字符。
package com.zetcode;
public class StringBuilderRemoveEx {
public static void main(String[] args) {
var sentence = "There is a red fox in the forest.";
var builder = new StringBuilder(sentence);
builder.delete(11, 14);
System.out.println(builder);
builder.deleteCharAt(11);
System.out.println(builder);
}
}
该示例从字符串中删除几个字符。
builder.delete(11, 14);
使用 delete 方法,我们删除由索引指定的子字符串。
builder.deleteCharAt(11);
使用 deleteCharAt 方法,我们删除一个字符;在我们的例子中,它是一个多余的空格字符。
There is a fox in the forest. There is a fox in the forest.
Java StringBuilder 子字符串
使用 substring 方法,可以从字符串返回子字符串。
package com.zetcode;
public class StringBuilderSubstringsEx {
public static void main(String[] args) {
var sentence = "There is a red fox in the forest.";
var builder = new StringBuilder(sentence);
var word = builder.substring(15, 18);
System.out.println(word);
var sbstr = builder.substring(15);
System.out.println(sbstr);
}
}
在该示例中,我们检索两个子字符串。
var word = builder.substring(15, 18);
此行检索起始索引为 15,结束索引为 18 的子字符串。
var sbstr = builder.substring(15);
在这里,我们检索从索引 15 到句子结尾的子字符串。
fox fox in the forest.
来源
在本文中,我们使用了 Java StringBuilder。
作者
列出所有Java教程。