1. Introduction
1.绪论
In this quick tutorial, we’ll demonstrate how to add a character at any given position in a String in Java.
在这个快速教程中,我们将演示如何在Java中的字符串中的任何指定位置添加一个字符。
We’ll present three implementations of a simple function which takes the original String, a character and the position where we need to add it.
我们将介绍一个简单函数的三种实现,该函数接收原始String,一个字符和我们需要添加它的位置。
Since the String class is final and immutable the function should return a new String with the added character.
由于String类是final和immutable,该函数应该返回一个新的String,并添加了字符。
2. Using a Character Array
2.使用字符集Array
Here, the idea is to create a new character array and copy the characters from the original String before the given position.
这里,我们的想法是创建一个新的字符数组,并从原String中复制给定位置前的字符。
After that, we put the new character at the position and copy the rest of the characters from the original String in the subsequent positions of the new array.
之后,我们将新的字符放在这个位置,并将原String中的其余字符复制到新数组的后续位置。
Finally, we construct the desired String from that array.
最后,我们从该数组中构建所需的String。
public String addChar(String str, char ch, int position) {
int len = str.length();
char[] updatedArr = new char[len + 1];
str.getChars(0, position, updatedArr, 0);
updatedArr[position] = ch;
str.getChars(position, len, updatedArr, position + 1);
return new String(updatedArr);
}
Compared to the other two methods, this is a low-level design approach and gives us the most flexibility.
与其他两种方法相比,这是一种低层次的设计方法,给了我们最大的灵活性。
3. Using the substring Method
3.使用子串方法
An easier and higher level approach is to use the substring() method of the String class. It prepares the String by concatenating:
一个更简单和更高层次的方法是使用String类的substring()方法。它通过连接来准备String。
- The substring of the original String before the position
- The new character
- The substring of the original String after the position
public String addChar(String str, char ch, int position) {
return str.substring(0, position) + ch + str.substring(position);
}
Although the above code is more readable, it has a downside in that it creates a number of temporary objects to determine the result. As String is an immutable class, every call to its substring() method creates a new String instance.
虽然上面的代码更易读,它有一个缺点,即它创建了一些临时对象来确定结果。由于String是一个不可变的类,每次调用其substring()方法都会创建一个新的String实例。
Finally, when we concatenate the parts, the compiler creates a StringBuilder object for appending them one by one. Every String and StringBuilder object allocates separate memory locations for its internal character array.
最后,当我们连接这些部分时,编译器会创建一个StringBuilder对象来逐一追加它们。每个String和StringBuilder对象都为其内部字符数组分配单独的内存位置。
This implementation also needs to copy all the characters thrice from one array to another.
这个实现也需要将所有的字符从一个数组中复制三次到另一个数组中。
If we need to call the method a huge number of times, the temporary objects may fill the heap memory and that will trigger GC very frequently. This can also affect the performance to some extent.
如果我们需要调用大量的方法,临时对象可能会填满堆内存,这将会非常频繁地触发GC。这也会在一定程度上影响性能。
4. Using a StringBuilder
4.使用一个StringBuilder
StringBuilder is a utility class provided by Java library to construct and manipulate String objects in a number of ways.
StringBuilder是一个由Java库提供的实用类,用于以多种方式构造和操作String对象。
We can implement the same functionality using the insert() method of the StringBuilder class:
我们可以使用StringBuilder类的insert()方法实现同样的功能。
public String addChar(String str, char ch, int position) {
StringBuilder sb = new StringBuilder(str);
sb.insert(position, ch);
return sb.toString();
}
The above code needs to create only a single StringBuilder object to insert the character at the position. It allocates the same amount of memory that the original String has, but to create a place for the new character the underlying array shifts the next characters by 1 position.
上面的代码只需要创建一个StringBuilder对象来插入该位置的字符。它分配了与原始String相同的内存量,但是为了给新的字符创造一个位置,底层数组将下一个字符移动了一个位置。
Although using a StringBuilder may be slower, it doesn’t have the memory burden of initializing temporary objects. We also end up with code that is simple and readable.
尽管使用StringBuilder可能会慢一些,但它没有初始化临时对象的内存负担。我们最终得到的代码也是简单的、可读的。
5. Conclusion
5.总结
In this article, we focused on several ways of adding a character in a String object in Java. We’ve seen that the implementation using a character array offers the best performance and that with the substring method gives a more readable approach.
在这篇文章中,我们重点讨论了在Java对象中添加字符的几种方法。我们看到,使用字符数组的实现方式提供了最好的性能,而使用substring方法则提供了更多的可读性方法。
The preferred way of implementing the solution is using the StringBuilder class – as it’s simple, less bug-prone and offers good and stable performance.
实现该解决方案的首选方式是使用StringBuilder类–因为它很简单,不容易出错,并提供良好和稳定的性能。
As usual, the complete source code for the above tutorial is available over on GitHub.
像往常一样,上述教程的完整源代码可在GitHub上获取。