I need to create an algorithm to replace the chars of a String by the char indexes of a given sequence if the text char is available in the sequence, for example:
The sequence : 'acdfgijloprtuvx' The input : "Hello" The output must be : "He778"
'l' was replaced by 7 because it's the 7th index in the sequence.
Here's the code I started creating:
public static String encrypt(String str) {
String sequence = "acdfgijloprtuvx";
String result = "";
for(int i = 0; i < str.length(); i++) {
for(int j = 0; j < sequence.length(); j++) {
if(str.contains(sequence)) {
result = str.replace(str.charAt(i), sequence.charAt(j));
// I don't know what to do next
}
}
}
}
}
Consider the following solution, it only requires a single loop and makes use of indexOf
, and most importantly we correctyl use charAt
to get the current letter for each loop cycle to constrect the new string using result +=...
which is the same as result = result +...
:
String sequence = "acdfgijloprtuvx";
String result = "";
//value to hold the current letter
String letter;
for(int i = 0; i < str.length(); i++) {
//Get the current letter
letter = str.charAt(i) + "";
//If the sequence contains the letter
if (sequence.contains(letter)){
//Find the index of the letter and add it to the result
result += sequence.indexOf(letter);
}
//Else add the original unencoded character to the result
else{
result += letter;
}
}
//Print result
System.out.println("Result: " + result);
This prints the output Result: He778
The issue you were facing is that you attempted to compare the whole word with the whole sequence if(str.contains(sequence))
and you always wrote over previous data result = str.replace(str.charAt(i), sequence.charAt(j));
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.