I am trying to take a part of a String from point(a,b) and replace letters from given values in the string into 'X's.
Example: If the string is ABC123
and switch(3,5)
is called, it would change it to ABCXXX
.
So far I have:
public void switch(int p1, int p2)
{
String substring = myCode.substring(p1,p2-1);
}
I am very lost....thanks for any help!
Java String
s are immutable and can not be changed. You could however, write a method that returns a new String
with those characters marked out. A StringBuilder
is a good class to familiarize yourself with as it allows for fast string manipulations.
StringBuilder documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
public class StringReplace {
public static String replaceRange(String s, int start, int end){
StringBuilder b = new StringBuilder(s);
for(int i = start; i <= end; i++)
b.setCharAt(i, 'x');
return b.toString();
}
public static void main(String[] args){
String test = "mystringtoreplace";
String replaced = replaceRange(test, 3, 8);
System.out.println(replaced);
}
}
Use StringBuilder
and its replace(int start, int end, String str)
method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With