Change a single character of a string - java [closed]

-1

If I have a string of 10 characters where all these are 0 and I want the character #X and # 2X to change the 0 to 1, is there any function for it?

    
asked by Shiro 23.08.2017 в 16:53
source

3 answers

2

You can use the Substring to replace the characters, as follows:

int n1 = 2
int n2 = 5
String texto= "0000000000";
String nuevotexto = texto.substring(0,n1-1)+'1'+texto.substring(n1 +1,n2-1)+'1'+texto.substring(n2+1);

In this way you will get 0010010000 . Replacing positions 2 and 5 as indicated by the variables n1 and n2 .

    
answered by 23.08.2017 / 17:03
source
1

you could use the replace () method of the StringBuilder class

    String original = "0000000000";// cadena original original
    System.out.println("Original: " + original);
    int x = 4;// indice del caracter a reemplazar(empieza a contar en cero)
    String nuevo = new StringBuilder(original).replace(x, x+1, "1").toString();// nueva cadena reemplazando el caracter x de la original por 1
    nuevo = new StringBuilder(nuevo).replace(2*x, 2*x+1, "1").toString();// nuevo cadena reemplazando el caracter 2x de la cadena anterior
    System.out.println("Despues de reemplazar en el indice x = " + x + " y 2x = " + (2*x) + " : "  + nuevo);

With this you would get the string "0000100010" since the character is replaced in index 4 and 8 of the original chain.

    
answered by 23.08.2017 в 17:14
0

To modify the character in a specific position you can simply use

char[] tempCharArray = tuString.toCharArray();
tempCharArray[x] = '1'; // Donde 'x' es la posición que buscas.
tuString = String.valueOf(tempCharArray);
    
answered by 23.08.2017 в 17:02