Reemplazar un carácter en un índice específico en una cadena?


Estoy tratando de reemplazar un carácter en un índice específico en una cadena.

Lo que estoy haciendo es:

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

Esto da un error. ¿Hay algún método para hacer esto?

Author: jww, 2011-08-05

8 answers

Las cadenas son inmutables en Java. No puedes cambiarlos.

Necesita crear una nueva cadena con el carácter reemplazado.

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

O puedes usar un constructor de cadenas:

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

System.out.println(myName);
 458
Author: Petar Ivanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-21 02:25:11

Convierta la cadena en un char [], reemplace la letra por index, luego convierta la matriz de nuevo en una cadena.

String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
 114
Author: 16dots,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-10 21:11:14

String es una clase inmutable en java cualquier método que parezca modificarla siempre devuelve un nuevo objeto string con modificación. si desea manipular una cadena considere StringBuilder o StringBuffer en caso de que necesite thread safety

 17
Author: no name,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-05 07:00:12

Estoy de acuerdo con Petar Ivanov, pero es mejor si implementamos de la siguiente manera:

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);       
}
 11
Author: Leninkumar Koppoju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-03 07:38:22

Como se respondió anteriormente aquí, String las instancias son inmutables. StringBuffer y StringBuilder son mutables y adecuados para tal propósito, ya sea que necesite ser seguro para el hilo o no.

Sin embargo, hay una forma de modificar una Cadena, pero nunca la recomendaría porque no es segura, no es confiable y puede considerarse una trampa : puede usar reflection para modificar el array interno char que contiene el objeto String. Reflection le permite acceder a campos y métodos que normalmente están ocultos en el ámbito actual (métodos privados o campos de otra clase...).

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();
    }
}
 5
Author: C.Champagne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-20 16:44:47

Puede sobrescribir una cadena, de la siguiente manera:

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

Tenga en cuenta que la cadena myName aparece en ambas líneas, y en ambos lados de la segunda línea.

Por lo tanto, aunque las cadenas pueden ser técnicamente inmutables, en la práctica, puede tratarlas como editables sobrescribiéndolas.

 4
Author: CodeMed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 19:00:07

Lo primero que debería haber notado es que charAt es un método y asignarle un valor usando el signo igual no hará nada. Si una cadena es inmutable, el método charAt, para realizar un cambio en el objeto string debe recibir un argumento que contenga el nuevo carácter. Desafortunadamente, la cadena es inmutable. Para modificar la cadena, necesitaba usar StringBuilder como sugirió el Sr. Petar Ivanov.

 0
Author: dpp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-20 07:58:11

Esto funcionará

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

Salida : domaxokz

 -6
Author: Diabolus Infernalis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-03 06:38:56