在 Java 中插入字符串
在 Java 中,有几种方法可以在一个字符串中插入另一个字符串,以下是几种常见的方法:

使用 String.substring() 和 +
public class StringInsertExample {
public static void main(String[] args) {
String original = "HelloWorld";
String toInsert = " ";
int position = 5;
String result = original.substring(0, position) +
toInsert +
original.substring(position);
System.out.println(result); // 输出: Hello World
}
}
使用 StringBuilder
public class StringInsertExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("HelloWorld");
sb.insert(5, " ");
String result = sb.toString();
System.out.println(result); // 输出: Hello World
}
}
使用 String.format()
public class StringInsertExample {
public static void main(String[] args) {
String original = "HelloWorld";
String toInsert = " ";
int position = 5;
String result = String.format("%s%s%s",
original.substring(0, position),
toInsert,
original.substring(position));
System.out.println(result); // 输出: Hello World
}
}
使用 Apache Commons Lang (StringUtils)
如果你使用 Apache Commons Lang 库,可以使用 StringUtils.overlay() 方法:
import org.apache.commons.lang3.StringUtils;
public class StringInsertExample {
public static void main(String[] args) {
String original = "HelloWorld";
String toInsert = " ";
int position = 5;
String result = StringUtils.overlay(original, toInsert, position, position);
System.out.println(result); // 输出: Hello World
}
}
性能比较
- 对于少量字符串操作,
String.substring()和 运算符足够高效 - 对于大量或频繁的字符串操作,
StringBuilder是最佳选择,因为它不会创建多个中间字符串对象 StringBuilder.insert()方法是最直接和高效的方式
选择哪种方法取决于你的具体需求和性能考虑。

