There are two
replace methods in the String class api (javadocs Method Summary). One takes single
char arguments. This won't work because hex strings will likely be longer than a single
char. The other method takes CharSequence interface arguments. Looking up the CharSequence interface we see it has four methods and is implemented by (look up top under "All Known Implementing Classes:" the String class. Therefore, String must implement the methods defined in the interface. So we can use the
subSequence method to convert from String to CharSequence for the
replace method.
public class Test {
public static void main(String[] args) {
String s = "hello";
System.out.println("s = " + s);
int len = s.length();
int index = len/2;
char c = s.charAt(index);
int n = (int)c;
String hex = Integer.toHexString(n);
System.out.println("hex = " + hex);
CharSequence target = s.subSequence(index, index+1);
CharSequence replacement = hex.subSequence(0, hex.length());
s = s.replace(target, replacemment);
System.out.println("s = " + s);
}
}