New to java. Trying to familiarize myself with syntax and overall language structure.
I am trying to mimic this php function in java which just converts all instances of a number to a particular character
for($x=10;$x<=20;$x++){
$string = str_replace($x, chr($x+55), $string);
}
so in php if a string was 1090412 it would be converted to something like A904C.
I am trying to do this in java by using string.replace but I cant for the life of me figure out how to cast the variables properly. I know that I can convert an integer to a character by casting it as (char), but not sure where to go from there. this gives me a compile error expecting a character set.
string=1090412;
for (x = 10; x <= 35; x++) {
string.replace( x, (char) (x + 55));
}
Well, although not the best way to do this, here is a method that works
import java.lang.*;
public class T {
public static void main(String[] args) {
String s = "1090412";
for (int i = 10; i <= 20; i++) {
s = s.replace(Integer.toString(i), "" + (char)(i + 55));
}
System.out.println(s);
}
}
The java.lang.String
object has a replace method on it. It is overloaded to take either two char parameters or two CharSequence
objects. The "" + (char)(i + 55)
is just a quick way to create a CharSequence.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.