在 Java 中将一个字符串插入另一个字符串

2025 年 1 月 6 日 | 阅读 5 分钟

给定字符串的任务是在 Java 中将一个新字符串插入到给定字符串的特定索引处。

Insert a String into another String in Java

示例 1

输入

StringOriginal = "Hello World",

InsertedString = "Welcome To ",

Atindex = 5

输出

插入另一个字符串后的字符串是 "Hello, Welcome To World."

示例 2

输入

StringOriginal = "JAVALanguage",

InsertedString = " is a programming ",

Atindex = 3

输出

插入另一个字符串后的字符串是 JAVA is a programming Language

有多种方法可以实现此任务,如下所示。

方法:不使用任何预定义方法

通过应用此技术,我们将遍历字符串直到到达用户指定的索引。到达索引值后,将第二个字符串的元素添加到新字符串中,然后继续处理原始字符串。

算法

第 1 步:确定索引和字符串。

第 2 步:创建原始字符串

第 3 步:遍历字符串并将其复制到新字符串后,复制指定索引处的文本。

第 4 步:创建将要插入到新字符串中的字符串的副本。

第 5 步:将第一个字符串的剩余字符移到新字符串。

第 6 步:打印或返回新字符串。

实施

文件名: StringInsertionPredefined.java

输出

The Original String given is : Hello World
The String that has to be inserted is :  Welcome To
The String that has to be inserted at the index: 5
The string after the insertion of another string is : Hello, Welcome To World

复杂度分析

时间复杂度为 O(n),其中 n 是原始字符串的长度,因为循环会遍历字符串中的每个字符。但是,由于 Java 的 '+' 运算符的字符串连接具有 O(n) 的时间复杂度,因此当为原始字符串中的每个字符构造新字符串并将其与要插入的字符串连接时,总时间复杂度会增加到 O(n2)。

方法:使用 StringBuffer.insert() 方法

算法

第 1 步:获取索引和字符串。

第 2 步:创建新的 StringBuffer

第 3 步:使用 StringBuffer.insert() 将 stringToBeInserted 插入到原始字符串中。

第 4 步:使用 StringBuffer.toString() 函数从缓冲区返回或打印字符串。

实施

文件名: StringInsertionUsingBuffer.java

输出

The Original String given is : Hello World
The String that has to be inserted is :  Welcome To 
The String that has to be inserted at the index: 5
The string after the insertion of another string is : Hello, Welcome To World

复杂度分析

上述代码的时间复杂度为 O(n),其中 n 是原始字符串的长度。这是因为 StringBuffer 类的 insert() 方法需要移动插入点之后的字符以容纳新字符串,这导致 O(n) 的时间复杂度。

方法:使用 String.substring() 方法

算法

第 1 步:获取索引和字符串。

第 2 步:构建新字符串

第 3 步:使用 substring (0, index+1) 技术将从 0 到指定索引 (index + 1) 的子字符串插入。

第 4 步:接下来,将要插入的字符串滑入字符串。然后,使用 substring(index+1) 方法将原始字符串的其余部分插入到新字符串中。

第 5 步:打印或返回新字符串

实施

文件名: StringInsertionUsingSubString.java

输出

The Original String given is : Hello World
The String that has to be inserted is :  Welcome To 
The String that has to be inserted at the index: 5
The string after the insertion of another string is : Hello, Welcome To World

复杂度分析

上述技术的时间复杂度为 O(n),其中 n 是原始字符串的长度。这是因为代码中两次使用了 O(n) 时间复杂度的 substring 方法。字符串连接也需要 O(n) 的时间。