在 Java 中将一个字符串插入另一个字符串
java 8object oriented programmingprogramming更新于 2025/6/26 17:37:17
假设我们有一个字符串"That's good!",我们需要在其中插入文本"no"。因此,结果字符串应该是"That's no good!" −
String str = "That's 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 = "That's good!"; String newSub = "no "; int index = 6; System.out.println("Initial String = " + str); System.out.println("Index where new string will be inserted = " + index); StringBuffer resString = new StringBuffer(str); resString.insert(index + 1, newSub); System.out.println("Resultant String = "+resString.toString()); } }
输出
Initial String = That's good! Index where new string will be inserted = 6 Resultant String = That's no good!