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