Reputation: 35
public String getEncryption(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
String sub = text.substring(i, i+1);
System.out.println(i + " = " + sub);
String en = encrypt_code[Integer.parseInt(sub)];
System.out.println("Result:" + en);
x = x.concat(en);
}
return x;
}
I have this coding which works perfectly but I need to know how to use the charAt method to convert this and works in the same way? I have this so far
public String getEncryption2(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
char ch = text.charAt(i);
Upvotes: 2
Views: 651
Reputation: 691685
You're reading every char as a substring, and parse it as an int. So, you get for example "4" as the substring, and parse it to get the int 4.
If you use charAt()
, you'll get the char '4' instead. To transform it to the integer 4, you just need to subtract '0' from it:
String en = encrypt_code[ch - '0'];
Note that replacing the whole string by a new one at each iteration is time consuming. You should use a StringBuilder instead:
StringBuilder x = new StringBuilder();
for (...) {
x.append(en);
}
return x.toString();
Upvotes: 3