在字符串中替换特定索引中的字符?

时间:2022-09-13 08:45:00

I'm trying to replace a character at a specific index in a string.

我正在尝试用字符串替换特定索引中的字符。

What I'm doing is:

我做的是:

String myName = "domanokz";
myName.charAt(4) = 'x';

This gives an error. Is there any method to do this?

这给了一个错误。有什么方法可以做到这一点吗?

8 个解决方案

#1


417  

String are immutable in Java. You can't change them.

字符串在Java中是不可变的。你不能改变他们。

You need to create a new string with the character replaced.

您需要创建一个替换字符的新字符串。

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

或者你可以使用StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

#2


100  

Turn the String into a char[], replace the letter by index, then convert the array back into a String.

将字符串转换为char[],用索引替换字母,然后将数组转换为字符串。

String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);

#3


16  

String is an immutable class in java any methods which seem to modify it always return a new string object with modification. if you want to manipulate a string consider StringBuilder or StringBuffer in case you require thread safety

在java中,String是一个不可变的类,任何看起来修改它的方法总是返回一个带有修改的新字符串对象。如果您想要操作字符串,请考虑StringBuilder或StringBuffer,以防您需要线程安全。

#4


11  

I agree with Petar Ivanov but it is best if we implement in following way:

我同意Petar Ivanov的观点,但如果我们采用以下方法,那是最好的:

public String replace(String str, int index, char replace){     
    if(str==null){
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    }
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
}

#5


5  

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

如前所述,字符串实例是不可变的。StringBuffer和StringBuilder是可变的,适合于这样的目的,无论您是否需要线程安全。

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

但是,有一种方法可以修改字符串,但是我永远不会推荐它,因为它不安全,不可靠,而且它可以被认为是欺骗:您可以使用反射来修改字符串对象包含的内部char数组。反射允许您访问通常隐藏在当前范围中的字段和方法(来自另一个类的私有方法或字段…)。

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

#6


3  

You can overwrite a string, as follows:

您可以覆盖字符串,如下所示:

String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);  

Note that the string myName occurs on both lines, and on both sides of the second line.

注意,字符串myName发生在两行,在第二行的两侧。

Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.

因此,即使在技术上,字符串在技术上是不可变的,但是在实践中,您可以通过重写它们来处理它们。

#7


0  

First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.

首先我应该注意到,charAt是一种方法,用等号来赋值,它什么都不会做。如果字符串是不可变的,charAt方法,对字符串对象进行更改必须接收包含新字符的参数。不幸的是,字符串是不可变的。为了修改字符串,我需要使用Petar Ivanov先生建议的StringBuilder。

#8


-6  

this will work

这将工作

   String myName="domanokz";
   String p=myName.replace(myName.charAt(4),'x');
   System.out.println(p);

Output : domaxokz

输出:domaxokz

#1


417  

String are immutable in Java. You can't change them.

字符串在Java中是不可变的。你不能改变他们。

You need to create a new string with the character replaced.

您需要创建一个替换字符的新字符串。

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

或者你可以使用StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

#2


100  

Turn the String into a char[], replace the letter by index, then convert the array back into a String.

将字符串转换为char[],用索引替换字母,然后将数组转换为字符串。

String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);

#3


16  

String is an immutable class in java any methods which seem to modify it always return a new string object with modification. if you want to manipulate a string consider StringBuilder or StringBuffer in case you require thread safety

在java中,String是一个不可变的类,任何看起来修改它的方法总是返回一个带有修改的新字符串对象。如果您想要操作字符串,请考虑StringBuilder或StringBuffer,以防您需要线程安全。

#4


11  

I agree with Petar Ivanov but it is best if we implement in following way:

我同意Petar Ivanov的观点,但如果我们采用以下方法,那是最好的:

public String replace(String str, int index, char replace){     
    if(str==null){
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    }
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
}

#5


5  

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

如前所述,字符串实例是不可变的。StringBuffer和StringBuilder是可变的,适合于这样的目的,无论您是否需要线程安全。

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

但是,有一种方法可以修改字符串,但是我永远不会推荐它,因为它不安全,不可靠,而且它可以被认为是欺骗:您可以使用反射来修改字符串对象包含的内部char数组。反射允许您访问通常隐藏在当前范围中的字段和方法(来自另一个类的私有方法或字段…)。

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

#6


3  

You can overwrite a string, as follows:

您可以覆盖字符串,如下所示:

String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);  

Note that the string myName occurs on both lines, and on both sides of the second line.

注意,字符串myName发生在两行,在第二行的两侧。

Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.

因此,即使在技术上,字符串在技术上是不可变的,但是在实践中,您可以通过重写它们来处理它们。

#7


0  

First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.

首先我应该注意到,charAt是一种方法,用等号来赋值,它什么都不会做。如果字符串是不可变的,charAt方法,对字符串对象进行更改必须接收包含新字符的参数。不幸的是,字符串是不可变的。为了修改字符串,我需要使用Petar Ivanov先生建议的StringBuilder。

#8


-6  

this will work

这将工作

   String myName="domanokz";
   String p=myName.replace(myName.charAt(4),'x');
   System.out.println(p);

Output : domaxokz

输出:domaxokz