假设我们有一个字符串“That’sgood!”在其中我们需要插入文本“no”。因此,结果字符串应为“That’snogood!”-
String str = "Thats good!";
String newSub = "no ";
现在,将在其中插入新子字符串的索引-
int index = 6;
现在插入新的子字符串-
StringBuffer resString = new StringBuffer(str);
resString.insert(index + 1, newSub);
现在让我们看一个将字符串插入另一个的示例-
示例
import java.lang.*;
public class Main {
public static void main(String[] args) {
String str = "Thats good!";
String newSub = "no ";
int index = 6;
System.out.println("初始字符串 = " + str);
System.out.println("将插入新字符串的索引 = " + index);
StringBuffer resString = new StringBuffer(str);
resString.insert(index + 1, newSub);
System.out.println("结果字符串 = "+resString.toString());
}
}
输出结果
初始字符串 = Thats good!
将插入新字符串的索引 = 6
结果字符串 = Thats no good!