I am trying to code a method that will take a String input , and replace all the letter 'a's (upper and lower) with the first letter of a String mapping, all the letter 'b's w/ the second letter, and so on. I'm having some real trouble w/ this, for one, i'm not sure how you would go about incrementing a character through the alphabet.
public static String remap(String input, String mapping){
char c = 'a';
int i = 0;
StringBuffer buffer = new StringBuffer();
while(i %26lt; input.length() - 1){
if (input.indexOf(c) == i){
buffer.append(c);
i++;
c += 1;
}
}
return buffer.toString();
}
Java question?
you're not incrementing i if your if statement fails. That is, if 'a' doesn't exist in input, you will loop forever.
If I understand the problem correctly, I would:
input = input.toLowerCase();
while(i %26lt; input.length() - 1)
{
char offset = input.charAt(i);
offset = offset - 'a';
char newchar = mapping.charAt(offset);
buffer.append(newchar);
i++;
}
Something like that, anyway. Probably have to do some casting or conversion of strings to bytes since the types won't match up, but hopefully you get the drift. (This would work fine in C)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment