Replace a Character at a Specific Index in a String in Java – 在Java中替换一个字符串中特定索引的字符

最后修改: 2018年 12月 27日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this quick tutorial, we’ll demonstrate how to replace a character at a specific index in a String in Java.

在这个快速教程中,我们将演示如何在Java中替换String中某个特定索引的字符。

We’ll present four implementations of simple methods that take the original String, a character, and the index where we need to replace it.

我们将介绍四个简单方法的实现,这些方法接收原始String,一个字符,以及我们需要替换它的索引。

2. Using a Character Array

2.使用一个字符阵列

Let’s begin with a simple approach, using an array of char.

让我们从一个简单的方法开始,使用一个char.的数组。

Here, the idea is to convert the String to char[] and then assign the new char at the given index. Finally, we construct the desired String from that array.

这里,我们的想法是将String转换为char[],然后将新的char分配到给定的索引。最后,我们从该数组中构造所需的String

public String replaceCharUsingCharArray(String str, char ch, int index) {
    char[] chars = str.toCharArray();
    chars[index] = ch;
    return String.valueOf(chars);
}

This is a low-level design approach and gives us a lot of flexibility.

这是一种低级别的设计方法,给了我们很大的灵活性。

3. Using the substring Method

3.使用子串方法

A higher-level approach is to use the substring() method of the String class.

一个更高层次的方法是使用String类的substring()方法。

It will create a new String by concatenating the substring of the original String before the index with the new character and substring of the original String after the index:

它将创建一个新的String,将原String在索引前的子串与原String在索引后的新字符和子串连接起来。

public String replaceChar(String str, char ch, int index) {
    return str.substring(0, index) + ch + str.substring(index+1);
}

4. Using StringBuilder

4.使用StringBuilder

We can get the same effect by using StringBuilder. We can replace the character at a specific index using the method setCharAt():

我们可以通过使用StringBuilder获得同样的效果。我们可以使用setCharAt()方法替换特定索引处的字符:

public String replaceChar(String str, char ch, int index) {
    StringBuilder myString = new StringBuilder(str);
    myString.setCharAt(index, ch);
    return myString.toString();
}

5. Conclusion

5.总结

In this article, we focused on several ways of replacing a character at a specific index in a String using Java.

在这篇文章中,我们着重介绍了使用Java替换String中特定索引的字符的几种方法

String instances are immutable, so we need to create a new string or use StringBuilder to give us some mutability.

String 实例是不可变的,所以我们需要创建一个新的字符串或使用StringBuilder来给我们一些可变性。

As usual, the complete source code for the above tutorial is available over on GitHub.

像往常一样,上述教程的完整源代码可在GitHub上获取。