Replace a character at a specific index in a string?

后端 未结 8 910
我在风中等你
我在风中等你 2020-11-22 03:22

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\';


        
相关标签:
8条回答
  • 2020-11-22 03:36

    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.

    0 讨论(0)
  • 2020-11-22 03:41

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

    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 myName = new StringBuilder("domanokz");
    myName.setCharAt(4, 'x');
    
    System.out.println(myName);
    
    0 讨论(0)
  • 2020-11-22 03:43

    String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

    If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

    0 讨论(0)
  • 2020-11-22 03:45

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

    String myName = "domanokz";
    char[] myNameChars = myName.toCharArray();
    myNameChars[4] = 'x';
    myName = String.valueOf(myNameChars);
    
    0 讨论(0)
  • 2020-11-22 03:46

    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.

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

    0 讨论(0)
  • 2020-11-22 03:55

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

    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);       
    }
    
    0 讨论(0)
提交回复
热议问题