Replace a character at a specific index in a string?

后端 未结 8 927
我在风中等你
我在风中等你 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:57

    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.

    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...).

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:01

    this will work

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

    Output : domaxokz

    0 讨论(0)
提交回复
热议问题